本題的基本要求非常簡單:給定N個實數(shù),計算它們的平均值。但復雜的是有些輸入數(shù)據(jù)可能是非法的。一個“合法”的輸入是[-1000,1000]區(qū)間內(nèi)的實數(shù),并且最多精確到小數(shù)點后2位。當你計算平均值的時候,不能把那些非法的數(shù)據(jù)算在內(nèi)。
輸入格式:
輸入第一行給出正整數(shù)N(<=100)。隨后一行給出N個實數(shù),數(shù)字間以一個空格分隔。
輸出格式:
對每個非法輸入,在一行中輸出“ERROR: X is not a legal number”,其中X是輸入。最后在一行中輸出結果:“The average of K numbers is Y”,其中K是合法輸入的個數(shù),Y是它們的平均值,精確到小數(shù)點后2位。如果平均值無法計算,則用“Undefined”替換Y。如果K為1,則輸出“The average of 1 number is Y”。
輸入樣例1:75 -3.2 aaa 9999 2.3.4 7.123 2.35輸出樣例1:ERROR: aaa is not a legal numberERROR: 9999 is not a legal numberERROR: 2.3.4 is not a legal numberERROR: 7.123 is not a legal numberThe average of 3 numbers is 1.38輸入樣例2:2aaa -9999輸出樣例2:ERROR: aaa is not a legal numberERROR: -9999 is not a legal numberThe average of 0 numbers is Undefined#include <iostream>#include <cstdio>#include <string.h>using namespace std;int main() { int n, cnt = 0; char a[50], b[50]; double temp, sum = 0.0; cin >> n; for(int i = 0; i < n; i++) { scanf("%s", a); sscanf(a, "%lf", &temp); sPRintf(b, "%.2lf",temp); int flag = 0; for(int j = 0; j < strlen(a); j++) { if(a[j] != b[j]) { flag = 1; } } if(flag || temp < -1000 || temp > 1000) { printf("ERROR: %s is not a legal number/n", a); continue; } else { sum += temp; cnt++; } } if(cnt == 1) { 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"); } return 0;}
新聞熱點
疑難解答