1054 求平均值
本题的基本要求非常简单:给定 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
代码长度限制 16 KB
时间限制 200 ms
内存限制 64 MB
/*
1054 求平均值
https://pintia.cn/problem-sets/994805260223102976/exam/problems/994805272659214336
*/
#include <iostream>
#include <string>
#include <vector>
//判断是否是纯数字
bool isPureDigit(std::string& str)
{
int length=0;
for(int i=0;i<str.size();i++)
{
if(i==0&&str[i]=='-')
length++;
else if(str[i]=='.'&&i!=0)
length++;
else if(str[i]>='0'&&str[i]<='9')
length++;
}
if(length==str.size())
return true;
return false;
}
//判断是否是有多个小数点,并且如果是一个小数点,则后面最多两位小数
bool containManyDots(std::string& str)
{
int dotNum=0,xiaoshuSize=0;
for(auto it=str.begin();it!=str.end();it++)
if(*it=='.')
dotNum++;
int posDot=str.find('.');
if(posDot!=-1)
for(int i=posDot+1;i<str.size();i++)
xiaoshuSize++;
if(xiaoshuSize>2||dotNum>1)
return false;
return true;
}
//以上均符合转化为小数
bool strToDouble(std::string& str,double& value)
{
double temp=0,xiaoShu=0;
int zhengShu=0,xiaoshuSize=0;
bool fuHaoFlag=false,dotFlag=false;
int posDot=str.find('.');
for(int i=posDot+1;i<str.size();i++)
xiaoshuSize++;
for(int i=0;i<str.size();i++)
{
if(i==0&&str[i]=='-')
{
fuHaoFlag=true;
continue;
}
if(str[i]=='.'&&i!=0)
{
dotFlag=true;
continue;
}
if(!dotFlag)
zhengShu=zhengShu*10+(str[i]-'0');
else
xiaoShu=xiaoShu*10.0+(str[i]-'0');
}
if(xiaoshuSize!=0)
{
int chushu=1;
for(int i=0;i<xiaoshuSize;i++)
chushu*=10;
xiaoShu=xiaoShu/chushu;
}
temp=zhengShu+xiaoShu;
if(fuHaoFlag)
temp=-temp;
if(temp>-1000&&temp<1000)
{
value=temp;
return true;
}
return false;
}
int main()
{
int num;
double sum=0.0;
std::vector<double> v;
std::cin>>num;
for(int i=0;i<num;i++)
{
std::string temp;
double tempDouble;
std::cin>>temp;
//判断是否是纯数字,能把不是字母的过滤掉
if(!isPureDigit(temp))
{
std::cout<<"ERROR: "<<temp<<" is not a legal number\n";
continue;
}
//判断是否是有多个小数点,把多个小数点的过滤掉
if(!containManyDots(temp))
{
std::cout<<"ERROR: "<<temp<<" is not a legal number\n";
continue;
}
//以上均符合转化为小数,把超出范围的过滤掉
if(!strToDouble(temp,tempDouble))
{
std::cout<<"ERROR: "<<temp<<" is not a legal number\n";
continue;
}
v.push_back(tempDouble);
sum+=tempDouble;
}
if(v.size()==0)
printf("The average of 0 numbers is Undefined");
else if(v.size() == 1)
printf("The average of 1 number is %.2f", sum/v.size());
else
printf("The average of %ld numbers is %.2f", v.size(), sum/v.size());
}