**此题中的重要知识点:**字符串转换为浮点数
string str="12.56";//头文件#include<string>
double answer = atof (str.c_str());
//c_str()包含在<string>中,用于字符串str转换为char类型的字符数组
//atof()包含在<stdlib.h>中,用于将char类型字符数组转换为浮点数
题目要求:
本题的基本要求非常简单:给定 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
我的代码:
#include<iostream>
#include<cstdio>
#include<stdlib.h>
using namespace std;
int n;
bool isNum(string s){
if(s[0]='-'){//若有负号,去掉负号进行判断
s=s.substr(1);
}
int cnt=0;
for(int i=0;i<s.size();i++){
if(!isdigit(s[i])&&s[i]!='.'){//有除了'.'以外的字符
return false;
}
if(s[i]=='.'){//对字符串中的'.'进行计数
cnt++;
}
}
if(cnt==1){//只有一个'.'时,若小数点后位数太多,则返回false
int pos=s.find('.');
string behind = s.substr(pos+1);
if(behind.size()>2){
return false;
}
}
if(cnt>1){//有多余一个的'.' eg.输入样例中的2.3.4
return false;
}
return true;
}
bool isLegal(string s){//将字符串转换为浮点数判断是否在要求范围内
double result=atof(s.c_str());
if(result<=1000&&result>=-1000){
return true;
}
else{
return false;
}
}
int main(){
cin>>n;
double sum=0;
int cnt=0,total=n;
while(n--){
string s;
cin>>s;
if(!isNum(s)){//不是数字
cout<<"ERROR: "<<s<<" is not a legal number"<<endl;
}else{
if(!isLegal(s)){//是数字,但不在规定范围内
cout<<"ERROR: "<<s<<" is not a legal number"<<endl;
}else{//是符合要求的数字
double answer=atof(s.c_str());
sum+=answer;
cnt++;
}
}
}
if(cnt>1){
double average = sum / cnt;
printf("The average of %d numbers is %.2f",cnt,average);
}
else if(cnt==1){
printf("The average of 1 number is %.2f",sum);
}
else{
printf("The average of 0 numbers is Undefined");
}
return 0;
}