题目地址:PAT1054.求平均值
题目描述:
本题的基本要求非常简单:给定N个实数,计算它们的平均值。但复杂的是有些输入数据可能是非法的。一个“合法”的输入是[-1000,1000]区间内的实数,并且最多精确到小数点后2位。当你计算平均值的时候,不能把那些非法的数据算在内。
易错分析:
1. 只有一个合法的时候,打印的number不加s!!!
程序:
#include <iostream>
#include <cstdio>
#include <string.h>
#include <string>
using namespace std;
// 有一个陷阱,就是当number的个数是1的时候,输出应该是...number没有s
int main()
{
char a[50], b[50];
int N, cnt = 0;
double sum = 0.0, temp;
cin >> N;
while (N--)
{
int flag = 0;
scanf("%s", a);
/*sscanf与scanf类似,都是用于输入的,只是后者以屏幕(stdin)为输入源,
前者以固定字符串为输入源。*/
sscanf(a, "%lf", &temp);
// printf("%lf\n", temp); // 您可以打印看看
sprintf(b, "%.2lf", temp);
for (int i = 0; i < strlen(a); i++)
{ /* 用于判断最大精度为2且合法 */
if (a[i] != b[i])
{
flag = 1;
break;
}
}
if (flag == 1) // 如果不合法
{
printf("ERROR: %s is not a legal number\n", a);
}
else // 如果合法
{
if (temp <= 1000 && temp >= -1000)
{
sum += temp;
cnt++;
}
else
{
printf("ERROR: %s is not a legal number\n", a);
}
}
}
if (cnt == 1) { // 要注意这里的number不加s
printf("The average of 1 number is %.2lf", sum);
}
else if (cnt >= 1) {
printf("The average of %d numbers is %.2lf", cnt, sum / cnt);
}
else {
printf("The average of 0 numbers is Undefined");
}
}