1054 求平均值 (20 分)
- #include <cstdio>
- #include <cstring>
- #include <string>
- #include <iostream>
- #include <cmath>
- #include <algorithm>
- #include <iomanip>
- using namespace std;
- bool check(string &str)
- {
- bool flag=false;
- int i=0,a=0,b=0;
- if(str[i]=='-') i++;
- for(;i<str.size();i++)
- {
- if((!isdigit(str[i]))&&(str[i]!='.')) return false;
- if(str[i]=='.')
- {
- a++;
- flag=true;
- continue;
- }
- if(flag) b++;
- }
- if(a>1||b>2||stod(str)>1000||stod(str)<-1000) return false;
- else return true;
- }
- int main()
- {
- int n,count=0;
- string str;
- double sum=0;
- cin>>n;
- for(int i=0;i<n;i++)
- {
- cin>>str;
- if(!check(str)) cout<<"ERROR:"<<str<<"is not a legal number\n";
- else if(check(str)){
- count++;
- sum+=stod(str);
- }
- }
- if(count==0) cout<<"The average of 0 numbers is Undefined\n";
- else if(count==1) cout<<"The average of 1 number is"<<fixed<<setprecision(2)<<sum<<endl;
- else printf("The average of %d numbers is %.2f\n",count,sum/count);
- return 0;
- }
来源: http://www.bubuko.com/infodetail-3392796.html