P1054 求平均值
转跳点:🐏
1054 求平均值 (20分)
本题的基本要求非常简单:给定 N 个实数,计算它们的平均值。但复杂的是有些输入数据可能是非法的。一个“合法”的输入是 [−1000,1000] 区间内的实数,并且最多精确到小数点后 2 位。当你计算平均值的时候,不能把那些非法的数据算在内。
输入格式:
输入第一行给出正整数 N(≤100)。随后一行给出 N 个实数,数字间以一个空格分隔。
输出格式:
对每个非法输入,在一行中输出 ERROR: X is not a legal number
,其中 X
是输入。最后在一行中输出结果:The average of K numbers is Y
,其中 K
是合法输入的个数,Y
是它们的平均值,精确到小数点后 2 位。如果平均值无法计算,则用 Undefined
替换 Y
。如果 K
为 1,则输出 The average of 1 number is Y
。
输入样例 1:
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35
输出样例 1:
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
输入样例 2:
2
aaa -9999
输出样例 2:
ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefined
这道题整体上上还是很简单的,毕竟就是求个平均数。
不过坑的地方就在于小数位的判断两位还是两位以上,这个需要动脑子了,不过如过你会sscanf和sprintf的话就可以很轻易的想到方法。
sscanf() : 从一个字符串中读进与指定格式相符的数据
sprintf():字符串格式化命令,主要功能是把格式化的数据写入某个字符串中
一个%lf读入,一个%。2lf写入,比较一下字符串的差别就好了,而且sscanf不会读入字母,嘿嘿,简直就是神兵利器~
最最最最重要的难点!count == 1 的时候,输出 number 不是 numbers,哭死我了。
AC代码
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char data1[40];
char data2[40];
int n, count = 0;
double temp, sum = 0.0;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%s", data1);
sscanf(data1, "%lf", &temp);
sprintf(data2, "%.2lf", temp);
//合法小数判断
int flag = 1;
for (int j = 0; data1[j] != '\0'; j++)
{
if (data1[j] != data2[j])
{
flag = 0;
break;
}
}
//整数合法性
if (0 == flag || temp < -1000 || temp > 1000)
{
printf("ERROR: %s is not a legal number\n", data1);
continue;
}
sum += temp;
count++;
}
if (0 == count)
{
printf("The average of 0 numbers is Undefined");
}
else
{
printf("The average of %d number%s is %.2f", 1 == count ? 1 : count, 1 == count ? "" : "s", 1 == count ? sum : sum / count);
}
return 0;
}
写完之后看来一下其他人的博客,发现这个思路也挺不错:
链接:🔗
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int count = 0, N;
double f, sum = 0;
/* Maxium scenario: -1000.00. So just need to read 8 chars(+ '\0' = 9) */
char s[9], *pEnd, *pDot, c;
scanf("%d", &N);
for(int i = 0; i < N; i++)
{
scanf("%8s", s); /* Just read up to 8 chars */
c = ungetc(getchar(), stdin); /* Read next char and push back */
f = strtod(s, &pEnd); /* pEnd -> converted floating number */
pDot = strchr(s, '.'); /* pDot -> (first) decimal point */
if(!isspace(c) /* string too long */
|| *pEnd /* not floating number */
|| (f > 1000 || f < -1000) /* out of range */
|| (pDot && pDot - s < strlen(s) - 3)) /* precision too high */
{
printf("ERROR: %s", s);
/* this can avoid overflow (we don't know how long input is) */
while(!isspace(c = getchar())) putchar(c);
printf(" is not a legal number\n");
}
else /* legel number */
{
count++;
sum += f;
}
}
if(count == 0) printf("The average of 0 numbers is Undefined\n");
if(count == 1) printf("The average of 1 number is %.2lf", sum);
if(count >= 2) printf("The average of %d numbers is %.2lf", count, sum / count);
return 0;
}
PTA不易,诸君共勉!