1054 Average Score 20

The basic requirement of this problem is very simple: given N real numbers, calculate their average. But the complication is that some input data may be illegal. A "legal" input is a real number in the interval [−1000,1000] and accurate to at most 2 decimal places. When you calculate the average, you can't count those illegal data.

Input format:

The first line of input gives a positive integer N (≤100). The next line gives N real numbers separated by a space.

Output format:

For each illegal input, output on one line ERROR: X is not a legal number, where Xis the input. Finally, output the result in one line: The average of K numbers is Y, where is Kthe number of legal inputs and Ytheir average value, accurate to 2 decimal places. If the average cannot be calculated, replace Undefinedwith Y. If K1, then output The average of 1 number is Y.

Input sample 1:

7
5 -3.2 aaa 9999 2.3.4 7.123 2.35

Output sample 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

Input sample 2:

2
aaa -9999

Output sample 2:

ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefin

After referring to Liushen's code, I found that using sscanf and sprintf is much simpler than using string to judge.

Analysis: Use sscanf and sprintf functions ~
sscanf() – read data that matches the specified format from a string
sprintf() – string formatting command, the main function is to write formatted data into a string

#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n,cnt = 0;
    char a[105],b[105];
    double sum = 0.0,temp = 0.0;
    cin>>n;
    for(int i = 0;i<n;i++){
        scanf("%s",a);
        sscanf(a,"%lf",&temp);
        sprintf(b,"%.2f",temp);
        int flag = 0;
        for(int i = 0;i<strlen(a);i++)
            if(a[i]!=b[i]) flag = 1;
        if(flag||temp<-1000||temp>1000){
            printf("ERROR: %s is not a legal number\n", a);
            continue;
        }
        else{
            sum += temp;
            cnt++;
        }
    }
    if(cnt == 1)
        printf("The average of 1 number is %.2f", sum);
    else if(cnt > 1)
        printf("The average of %d numbers is %.2f", cnt, sum / cnt);
    else
        printf("The average of 0 numbers is Undefined");
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_53514496/article/details/124982468