PAT(A)1108 Finding Average (20分)(玄学模拟)

在这里插入图片描述

Sample Input

7
5 -3.2 aaa 9999 2.3.4 7.123 2.35

Sample 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

思路:
判断输入的数字是不是规范,然后再求所有规范数的平均值。
这题我把check里的p用long long就有一个点过不了,double就过了。。。
玄学,可能是精度问题吧。
代码

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>

using namespace std;

typedef long long ll;
#define error 100001
#define endl '\n'

double check(string a)
{
    double ans = 0, p = 1;
    int f = 1;
    ll cnt = 0;
    if (a[0] == '-')
        f = -1;
    for (int i = a.size() - 1; i >= 0; --i)
    {
        if (a[0] == '-' && i == 0) break;
        if (!((a[i] >= '0' && a[i] <= '9') || a[i] == '.'))
            return error;
        if (a[i] >= '0' && a[i] <= '9')
        {
            ans = ans + (a[i] - '0') * p;
            p *= 10;
        }
        if (a[i] == '.')
        {
            cnt++;
            if (p > 100)
                return error;
            if (cnt > 1)
                return error;
            ans /= p * 1.0;
            p = 1;
        }
    }
    ans *= f;
    if (ans > 1000 || ans < -1000)
        return error;
    return ans;
}

int main()
{
    int n;

    cin >> n;
    int k = 0;
    double ksum = 0;
    string str;
    for (int i = 0; i < n; ++i)
    {
        cin >> str;
        double res = check(str);
        if (res != error)
        {
            ksum += res;
            k++;
        }
        else
        {
            cout << "ERROR: " << str << " is not a legal number" << endl;
        }
    }

    if (k == 0)
        cout << "The average of 0 numbers is Undefined" << endl;
    else if (k == 1)
        printf("The average of %d number is %.2lf\n", k, ksum * 1.0 / k);
    else
    {
        printf("The average of %d numbers is %.2lf\n", k, ksum * 1.0 / k);
    }

    getchar(); getchar();
    return 0;
}

发布了161 篇原创文章 · 获赞 7 · 访问量 7103

猜你喜欢

转载自blog.csdn.net/weixin_43778744/article/details/103973116