1108 Finding Average (20 分| 字符串,附详细注释,逻辑分析)
原创
©著作权归作者所有:来自51CTO博客作者nkgines的原创作品,请联系作者获取转载授权,否则将追究法律责任
写在前面
- 字符数组存储输入数字
- 通过
sscanf
、sprintf
处理读取字符串
-
cstdio
头文件下 -
sscanf(a, "%lf", &real_num);
: 将字符数组str中的内容以%lf
格式写到real_num
中(从左至右) -
sprintf(b, "%.2f",real_num);
: 把real_num
以%.2f
形式写到str字符数组中
- 题目较为简单,熟识
sscanf / sprintf
函数事半功倍。
测试用例
input:
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35
output:
ERROR: aaa is not a legal number
ERROR: 9999 is not a legal number
ERROR: 2.3.4 is not a legal number
ERROR: 7.123 is not a legal number
The average of 3 numbers is 1.38
input:
2
aaa -9999
output:
ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0
ac代码
#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int main() {
int n, cnt = 0;
char a[50], b[50];
double real_num = 0.0, sum = 0.0;
scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%s", a);
sscanf(a, "%lf", &real_num);
sprintf(b, "%.2f",real_num);
int flag = 0;
for(int j = 0; j < strlen(a); j++)
if(a[j] != b[j]) flag = 1;
if(flag || real_num < -1000 || real_num > 1000) {
printf("ERROR: %s is not a legal number\n", a);
continue;
} else {
sum += real_num;
cnt++;
}
}
if(cnt == 1)
printf("The average of 1 number is %.2f", sum);
else if(cnt > 1)
printf("The average of %d numbers is %.2f", cnt, sum / cnt);
else
printf("The average of 0 numbers is Undefined");
return 0;
}
知识点小结
// Write formatted data to string
int sprintf ( char * str, const char * format, ... );
// Read formatted data from string
int sscanf ( char * str, const char * format, ...);
/* sprintf example */
#include <stdio.h>
int main ()
{
char buffer [50];
int n, a=5, b=3;
n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
printf ("[%s] is a %d char long string\n",buffer,n);
return 0;
}
Output:
[5 plus 3 is 8] is a 13 char long
/* sscanf example */
#include <stdio.h>
int main ()
{
char sentence []="Rudolph is 12 years old";
char str [20];
int i;
sscanf (sentence,"%s %*s %d",str,&i);
printf ("%s -> %d\n",str,i);
return 0;
}