【PAT】(B)1054 求平均值 (20)
阿新 • • 發佈:2018-12-24
『題目』
本題的基本要求非常簡單:給定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
『思路』
思路依然很簡單,
三點要求:
除了符號外,只能包含數字和小數點;
小數點只能有一位;
小數點後最多有兩位。
這道題確實是非常的坑,題目很不嚴謹,像這種對輸出格式要求很高的題目,應該描述得更加清晰才是。
題目對 001、000.01、12. 這種資料居然都是接受的
第三個測試點是當K等於1的情況
第四個測試點是[-1000,1000]邊界情況。
『AC程式碼』
#include <iostream> #include <cstring> #include <cmath> #include <cstdlib> using namespace std; //字元轉換成數字 double tra(char *s) { double a=atof(s); return a; } int main() { int N; cin>>N; double ans,sum = 0,k = 0; char s[N+1][1000]; for(int i =0; i < N; i++) { scanf("%s",s[i]); //puts(s[i]); //cout<<endl; int len = strlen(s[i]),flag = 0,p = 0,p_ = 0; //cout<<"len ="<<len<<endl; if(s[i][0] == '-') {//判斷第一位是否是負號 for(int j = 1; j < len; j++) { if(s[i][j] == '.')//判斷有多少小數點 p++; if(p == 1) p_++;//p_判斷小數點後有多少位數 } for(int j = 1; j < len; j++) { if((!(s[i][j] >= '0' && s[i][j] <= '9') && s[i][j] != '.' ) || (p > 1) || p_ > 3 ) { cout<<"ERROR: "; printf("%s",s[i]); cout<<" is not a legal number"<<endl ; flag = 1; break; } } } else { for(int j = 0; j < len; j++) { if(s[i][j] == '.') p++; if(p == 1) p_++; } for(int j = 1; j < len; j++) { if((!(s[i][j] >= '0' && s[i][j] <= '9') && s[i][j] != '.') || (p > 1) || p_ > 3) {//如果 不是數字,或小數點數大於1,或小數點後位數多於2 則非法 cout<<"ERROR: "; printf("%s",s[i]); cout<<" is not a legal number"<<endl ; flag = 1; break; } } } if(!flag) { ans = tra(s[i]); //cout<<"ans="<<ans<<endl; if(abs(ans) <= 1000) { sum+=ans; //cout<<"sum="<<sum<<endl; k++; } else{ cout<<"ERROR: "; printf("%s",s[i]); cout<<" is not a legal number"<<endl ; } } } if(k == 0){ cout<<"The average of "<<k<<" numbers is Undefined"; } else if(k == 1){ cout<<"The average of "<<k<<" number is "; printf("%.2lf",sum/k); } else{ cout<<"The average of "<<k<<" numbers is "; printf("%.2lf",sum/k); } return 0; }
『寫在最後的一些話』
牛羊,說我每天寫PAT很水,作為一個蒟蒻,迷宮寫的真的很費精神啊,這裡錯那裡錯的,還不能寫一些簡單的(相對)PAT水一下麼,好吧好吧,每天除了基礎知識再加一篇PAT。
Stay hungry ,stay foolish。