本題的基本要求非常簡單:給定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
#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 8 chars */ c = ungetc(getchar(), stdin); /* If the next is non-white char, it is too long */ f = strtod(s, &pEnd); /* pEnd points to '\0' for a floating number */ pDot = strchr(s, '.'); /* find the decimal point */ if(!isspace(c) /* more than 8 chars */ || *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 array 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; }