#include <iostream> #include <cstring> #include <queue> #include <cmath> #include <unordered_map> #include <algorithm> #include <stack> # define LL long long using namespace std; int N; double candi; bool valid(string s){ int flag=1; if(s[0]=='-'){ if(s.size()==1){ return false; } flag=-1; s=s.substr(1,s.size()-1); } int dot=0; for(int j=0;j<s.size();j++){ if(s[j]=='.') dot++; if(!( (s[j]>='0' && s[j]<='9') || s[j]=='.' )){ return false; } } if(dot>1){ return false; } int dotpos=-1; for(int j=0;j<s.size();j++){ if(s[j]=='.'){ dotpos=j; break; } } if(dotpos==-1){ if(s.size()>4){ return false; } int num=stoi(s); if(num<=1000){ candi=flag*num; }else{ return false; } }else{ int rightpart=s.size()-1-dotpos; int leftpart=dotpos; if(rightpart>2 || leftpart>4){ return false; }else if(dotpos==s.size()-1){ int num=stoi(s.substr(0,s.size()-1)); candi=1.0*flag*num; }else if(dotpos==0){ int rightnum=stoi(s.substr(dotpos+1,rightpart)); candi=flag*(1.0*rightnum/pow(10,rightpart)); } else{ int leftnum=stoi(s.substr(0,dotpos)); int rightnum=stoi(s.substr(dotpos+1,rightpart)); candi=flag*(1.0*leftnum+1.0*rightnum/pow(10,rightpart)); } if(candi<-1000.0 || candi>1000.0){ return false; } } return true; }; int main(){ scanf("%d", &N); int ilcnt=0; double res=0.0; for(int i=0;i<N;i++){ string s; cin>>s; bool r=valid(s); if(!r){ cout<<"ERROR: "<<s<<" is not a legal number"<<" "; ilcnt++; }else{ res+=candi; } } if(ilcnt==N){ printf("The average of 0 numbers is Undefined "); }else if(N-ilcnt>1){ double avg=res/(N-ilcnt); printf("The average of %d numbers is %.2f ", N-ilcnt, avg); }else{ double avg=res/(N-ilcnt); printf("The average of %d number is %.2f ", N-ilcnt, avg); } return 0; }
利用 sscanf, sprintf :
#include <iostream> #include <cstring> #include <queue> #include <cmath> #include <unordered_map> #include <algorithm> #include <stack> # define LL long long using namespace std; int N; char a[50], b[50]; double candi; int main(){ scanf("%d", &N); int ilcnt=0; double res=0.0; for(int i=0;i<N;i++){ int flag=1; scanf("%s", a); sscanf(a,"%lf",&candi); sprintf(b,"%.2f", candi); for(int j=0;j<strlen(a);j++){ if(a[j]!=b[j]){ flag=0; break; } } if(flag==0 || candi<-1000 || candi>1000){ ilcnt++; printf("ERROR: %s is not a legal number ", a); }else{ res+=candi; } } if(ilcnt==N){ printf("The average of 0 numbers is Undefined "); }else if(N-ilcnt>1){ double avg=res/(N-ilcnt); printf("The average of %d numbers is %.2f ", N-ilcnt, avg); }else{ double avg=res/(N-ilcnt); printf("The average of %d number is %.2f ", N-ilcnt, avg); } return 0; }