pat乙級1054求平均數
阿新 • • 發佈:2018-12-24
這個題目比較坑在number和numbers上面。容易漏掉負號。容易漏掉小數點問題。pritnf輸出string還是會出錯。慎重選擇吧。
cin>>num[]也是合法的。
程式碼
//最初出錯在一個坑人的地方。num沒有初始化,本地通過了,oj沒有通過。果然厲害。以後一定記得要初始化啊。還有number 和numbers的問題。 #include<iostream> #include<stdlib.h> #include<string> #include<sstream> using namespace std; int main(){ char temp; string s; int n; char a[100][100]; int count=0,fcount=0,subcount=0; bool not_legal,after_float; cin>>n; int num=0; float number=0,legal; // while(cin>>s) for(int i=0;i!=n;i++) { cin>>s; not_legal =false; after_float=false; count=0; fcount=0; subcount=0; istringstream stream(s); while(stream>>temp){ if(temp=='.'){ after_float=true; count++; } else if(temp>'9'||temp<'0'){ not_legal=true; if(temp=='-'&&subcount==0){ subcount++; not_legal=false; } } if(after_float){ fcount++; } if(count>1){ not_legal=true; } if(fcount>3){ not_legal=true; } } istringstream stm(s); stm>>legal; if(legal>1000||legal<-1000){ not_legal=true; } if(not_legal){ //printf("ERROR: %s is not a legal number\n",s); cout<<"ERROR: "<<s<<" is not a legal number"<<endl; } else{ num++; // istringstream stream(s); // stream>>legal; number+=legal; } } if(num){ if(num==1){ printf("The average of %d number is %.2f\n",num,number/num); } else{ printf("The average of %d numbers is %.2f\n",num,number/num); } // printf("The average of %d numbers is %.2f\n",num,number/num); } else{ printf("The average of 0 numbers is Undefined\n"); } return 0; }