AcWing 1598. 求平均值
原题链接
简单
作者:
leo123456
,
2020-09-04 16:40:55
,
所有人可见
,
阅读 548
#include<iostream>
using namespace std;
bool isdigital(char c)
{
if(c>='a'&&c<='z'||c>='A'&&c<='Z') return false;
else return true;
}
bool istwo(char c)
{
if(c=='.') return true;
else return false;
}
int main()
{
int n;
cin>>n;
int cnt=0;
double sum=0;
while(n--)
{
string num;
cin>>num;
double x;
bool success=true;
for(int i=0;i<num.size();i++)
{
if(!isdigital(num[i]))
{
success =false;
break;
}
}
int count=0;
for(int i=0;i<num.size();i++)
{
if(istwo(num[i]))
{
count++;
}
}
if(count>1) success=false;
x=stod(num);
if(x<-1000||x>1000) success=false;
int k=num.find(".");
if(k!=-1&&num.size()-k>3) success=false; //存在小数点并且多余两位有效数字
if(success) cnt++,sum+=x;
else printf("ERROR: %s is not a legal number\n",num.c_str());
}
if(cnt>1) printf("The average of %d numbers is %.2lf\n",cnt,sum/cnt);
else if(cnt==1) printf("The average of 1 number is %.2lf\n",sum);
else printf("The average of 0 numbers is Undefined\n") ;
return 0;
}
如果num里存在除字母外的其余字符,这个判断条件行不通