其他分享
首页 > 其他分享> > B1054 求平均值 (20 分 | 字符串处理,附详细注释,逻辑分析)

B1054 求平均值 (20 分 | 字符串处理,附详细注释,逻辑分析)

作者:互联网

写在前面

测试用例

input:
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35

output:
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:
2
aaa -9999

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

ac代码

#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;

int main()
{
    int n, cnt = 0;
    cin >> n;

    char a[50],b[50];
    double tmp, sum = 0.0;
    for(int i=0; i<n; i++)
    {
        scanf("%s", a);
        sscanf(a, "%lf", &tmp);
        sprintf(b, "%.2f", tmp);
        int flag = 0;
        for(int j=0; j<strlen(a); j++)
            if(a[j]!=b[j]) flag = 1;
        if(flag || tmp<-1000 || tmp>1000)
        {
            printf("ERROR: %s is not a legal number\n", a);
            continue;
        }
        else
        {
            sum+=tmp;
            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;
}

知识点小结

标签:20,int,number,legal,B1054,char,numbers,ERROR,字符串
来源: https://blog.csdn.net/qq_24452475/article/details/100185336