PAT 1108 Finding Average (20)

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

题目大意:判断输入的字符串是否在[-1000, 1000] ,并且小数点不超过2位; 计算合法数字的平均数;
思路:用sscanf()把输入的字符串转化为数字temp,在用sprintf()把temp按照两位小数转化为字符串b; 在a和b的长度范围内判断两个字符串的内容是否一致,如果不一致肯定不是合法的数字; 此外还可能存在这一的情况
a对于的数字没有小数部分,当把temp转换为b的时候,会在b后面添加".00"; 用上面的方法判断就会出错;对于这种情况, 如果b的长度比a小,则肯定不是合法数字
 1 #include<iostream>
 2 #include<cctype>
 3 #include<string>
 4 #include<vector>
 5 #include<cstring>
 6 using namespace std;
 7 int main(){
 8     int n, i, cnt=0;
 9     cin>>n;
10     double temp=0.0, sum=0.0;
11     for(i=0; i<n; i++){
12         char a[60], b[60];
13         scanf("%s", a);
14         sscanf(a, "%lf", &temp);
15         sprintf(b, "%.2f", temp);
16         int flag=1;
17         for(int j=0; j<strlen(b) && j<strlen(a); j++){
18             if(a[j]!=b[j]){
19                 flag=0;
20                 break;
21             }
22         }
23         if(strlen(a)>strlen(b)) flag=0;
24         if(flag && (temp<=1000 && temp>=-1000)) {
25             sum += temp;
26             cnt++;
27         }
28         else printf("ERROR: %s is not a legal number
", a);
29     }
30     if(cnt>1) printf("The average of %d numbers is %.2f
", cnt, sum/(cnt*1.0));
31     else if(cnt==1) printf("The average of %d number is %.2f
", cnt, sum);
32     else printf("The average of 0 numbers is Undefined
");
33 return 0;}
有疑惑或者更好的解决方法的朋友,可以联系我,大家一起探讨。qq:1546431565
原文地址:https://www.cnblogs.com/mr-stn/p/9232229.html