注意字符串和数字之间的相互转换
#include <iostream>
#include<string>
#include <cmath>
using namespace std;
bool judge(string& string1){
int count=0;
for (int i1=0;i1<string1.length();i1++) {
char i=string1[i1];
if (!(i=='.'||isdigit(i)||i=='-')){
return false;
}
if(i=='.'){
count++;
if(string1.length()-i1>3){
return false;
}
}
if(count==2){
return false;
}
}
return true;
}
int main() {
// std::cout << "Hello, World!" << std::endl;
int N;
cin>>N;
double sum=0;
int count=0;
for (int i = 0; i < N; ++i) {
string s;
cin>>s;
if(judge(s)){
double val;
sscanf(s.c_str(),"%lf",&val);//字符串转化为数字
if (abs(val)>1000){
printf("ERROR: %s is not a legal number\n",s.c_str());
continue;
}
sum+=val;
count++;
} else{
printf("ERROR: %s is not a legal number\n",s.c_str());
}
}
if(count==0){
cout<<"The average of 0 numbers is Undefined";
return 0;
} else if(count==1){
cout<<"The average of 1 number is ";
printf("%.2f\n",sum);
return 0;
}
cout<<"The average of "<<count<<" numbers is ";
printf("%.2f\n",sum/count);
return 0;
}