pat1108 Finding Average

题意:输入n个字符串,选出合法的数字字符串,求平均值。

思路:ifelse判断一下合法字符就好。

代码

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

using namespace std;

const int MAX_N = 10;

char s[MAX_N];
int len, N, t;
double sum;

bool isNum(char s[]) {
    len = strlen(s);
    int cnt = 1, num = 0;
    for (int i = 0; i < len; i++) {
        if (cnt == 0) {
            num++;
            if (num > 2) return false;
        }
        if (i == 0) {
            if (s[i] == '-' && len > 1) continue;
        }
        if (isdigit(s[i])) continue;
        if (s[i] == '.' && cnt > 0) {
            cnt--;
        } else {
            return false;
        }
    }
    return true;
}

int main() {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    scanf("%d", &N);
    t = 0;
    sum = 0.0;
    for (int i = 0; i < N; i++) {
        scanf("%s", s);
        if (isNum(s)) {
            double tmp = strtod(s, NULL);
            if (tmp < -1000 || tmp > 1000) {
                printf("ERROR: %s is not a legal number\n", s);
                continue;
            }
            sum += tmp;
            t++;
        } else {
            printf("ERROR: %s is not a legal number\n", s);
        }
    }
    if (t == 0) {
        printf("The average of 0 numbers is Undefined\n");
    } else if (t == 1) {
        printf("The average of 1 number is %.2lf\n", sum);
    } else {
        printf("The average of %d numbers is %.2lf\n", t, sum/t);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值