本题的基本要求非常简单:给定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 numberThe average of 0 numbers is Undefined
思路分析:没什么好说的注意特殊情况
代码如下:
#include<stdio.h> #include<stdlib.h> typedef struct { char p[10000000]; double a=0; int b=1; }hunger; int main() { int n,i=0,j=0,count=0; int flaga = 0, flags = 0, flagb = 0; int st; double ad,sum=0,av; char c,buff; scanf("%d", &n); hunger *list; list = (hunger *)malloc(sizeof(hunger)*n); for (i = 0; i < n; i++) { scanf("%s", list[i].p); list[i].b = 1; flaga = 0; flags = 0; flagb = 0; for (j = 0; list[i].p[j] != '\0'; j++) { c = list[i].p[j]; if (c == '-'||c=='+') { if (j != 0) { list[i].b = 0; break; } if (c == '-') { flags = -1; } else { flags = 1; } } else if (c == '.') { if (j == 0||(list[i].p[j-1]=='-'&&j==1)|| (list[i].p[j - 1] == '+'&&j == 1)) { list[i].b = 0; //flaga = 0; break; } if (flaga == 1) { list[i].b = 0; //flaga = 0; break; } if (flaga == 0) { flaga = 1; flagb = 1; } } else if (c >= '0'&&c <= '9') { if (flagb != 0) { flagb++; } if (flagb > 3) { list[i].b = 0; } } else if ((c<'0' || c>'9')) { list[i].b = 0; break; } } if (list[i].b == 1) { sscanf(list[i].p, "%lf", &list[i].a); // st = (int)(list[i].a * 100); // ad = 1; // ad = list[i].a * 100 - (double)st; //if (ad != 0) { // list[i].b = 0; //} // else { if (list[i].a < -1000|| list[i].a >1000) { list[i].b = 0; } } } for (i = 0; i < n; i++) { if (list[i].b == 0) { printf("ERROR: %s is not a legal number\n", list[i].p); } else { sum += list[i].a; count++; } } av = sum / (double)count; if(count>1) printf("The average of %d numbers is %.2f", count, av); else if (count == 1) { printf("The average of %d number is %.2f", count, av); } else if(count==0){ printf("The average of %d numbers is Undefined", count); } return 0; }