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
题意:
与乙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
思路:
用字符数组存取每一个数,然后用sscanf转为double型浮点数,然后再用sprintf将该浮点数保留两位小数转为字符数组,比较两字符数组是否相同
C++代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main(){
int n;
cin>>n;
double sum=0;
int count=0;
char str1[101],str2[101];
for(int i=0;i<n;i++){
scanf("%s",str1);
double d;
sscanf(str1,"%lf",&d);
sprintf(str2,"%.2lf",d);
bool flag=true;
for(int j=0;j<strlen(str1);j++){
if(str1[j]!=str2[j]){
flag=false;
break;
}
}
if(flag==false){
cout<<"ERROR: "<<str1<<" is not a legal number"<<endl;
}
else if(d>1000||d<-1000){
cout<<"ERROR: "<<str1<<" is not a legal number"<<endl;
}
else{
count++;
sum+=d;
}
}
if(count==0){
printf("The average of %d numbers is Undefined",count);
}
else if(count==1){
printf("The average of %d number is %.2f",count,sum/count);
}
else{
printf("The average of %d numbers is %.2f",count,sum/count);
}
return 0;
}