题目描述
求出合法数据的平均值并输出相应语句。对于不合法的数据我们要输出ERROR语句。
题目分析
这个问题其实乍一看挺简单的,但是有很多细节处理起来很麻烦。首先,我们需要写一个函数,对于每一个输入的字符串进行判断其是否合理。如果这个字符串中有两个小数点或者有一个小数点但是精确位数大于2则都不合理,如果不是数字也淘汰。
在我们的主函数中,我们逐一输入字符串,判断其是否合理,如果不合理就输出对应的ERROR语句。如果合理则记录下来留着计算平均值。
计算平均值时保留小数点后两位,且需要输出相应语句,如果全部不合理,则输出The average of 0 numbers is Undefined
还有一个细节,如果只有一个数计算平均值,则对应输出的是number
,否则为numbers
代码
#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++;
}
//stod将str类型的变量转化为double类型
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;
}
答题用时21min
Q54——finish√