题目来源:PAT (Advanced Level) Practice
The basic task is simple: given N real numbers, you are supposed to calculate their average. But what makes it complicated is that some of the input numbers might not be legal. A legal input is a real number in [−1000,1000] and is accurate up to no more than 2 decimal places. When you calculate the average, those illegal numbers must not be counted in.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤100). Then N numbers are given in the next line, separated by one space.
Output Specification:
For each illegal input number, print in a line ERROR: X is not a legal number
where X
is the input. Then finally print in a line the result: The average of K numbers is Y
where K
is the number of legal inputs and Y
is their average, accurate to 2 decimal places. In case the average cannot be calculated, output Undefined
instead of Y
. In case K
is only 1, output The average of 1 number is Y
instead.
Sample Input 1:
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35
Sample Output 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
Sample Input 2:
2
aaa -9999
Sample Output 2:
ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefined
words:
complicated 复杂的 accurate 精确的,准确的 decimal 十进制的,小数的
题意:
给出n个数,求这些数中是合法实数的数的平均值;
思路:
1. 以字符串的形式保存每一个数,因为有的数不是合法的实数,可能含有字母;
2. 判断每一个数是否为合法的实数,并记录合法实数的个数与和;
a. 若小数点后的数字超过2位则不是合法数;
b. 若数中有除小数点以外的非数字字符则不是合法数;
c. 若数中的小数点的个数大于1则不是合法数;
d.若数的值不在区间[-1000,1000]内则不是合法数;
3. 输出时要针对合法数的个数作不同输出(即针对0,1,大于1);
//PAT ad 1108 Finding Average
#include <iostream>
using namespace std;
#include <algorithm>
#include <sstream>
#include <iomanip>
bool isLegal(string s,double &sum)
{
int i=0;
if(s[0]=='-') i++;
int dot=0; //记录小数点的个数
int dotPos=s.find('.'); //小数点的位置
if(dotPos!=s.npos&&s.size()-dotPos>3) return false; //精确超过了小数点后两位
for(;i<s.size();i++)
{
if(!isdigit(s[i])&&s[i]!='.') return false; //字符不是数或小数点
if(s[i]=='.') dot++;
if(dot>1) return false; //小数点超过1个
}
double t;
stringstream str(s);
str>>t;
if(t<-1000||t>1000) return false;
sum+=t;
return true;
}
int main()
{
int n;
cin>>n;cin.ignore();
string s;
int c=0; //记录合法的实数个数
double sum=0;
while(n--)
{
cin>>s;
if(isLegal(s,sum))
c++;
else
cout<<"ERROR: "<<s<<" is not a legal number"<<endl; //错误信息输出
}
if(c==0)
cout<<"The average of "<<c<<" numbers is Undefined"; //输出
else if(c==1)
cout<<"The average of "<<c<<" number is "<<fixed<<setprecision(2)<<sum/c<<endl;
else
cout<<"The average of "<<c<<" numbers is "<<fixed<<setprecision(2)<<sum/c<<endl;
return 0;
}