1054 求平均值 (20分)

/*
题意:(字符串处理)
1、N个实数,求平均值,不要计算非法(1000正负,小数点两位

2、非法输出
最后输出几个数+平均值

也可以输出,0个数+ 没定义

解题
1、设置变量,n,cnt,a,b
然后设置temp以及sum(double)
2、for循环杜甫
3、输入这个字符
scanf读成double到a,spring读到b
4、for循环,判定a和b是否相同,不同则flag为1,在给一个for循环,判断temp是否在区间

learn && wrong:
1、如何判定结果才是重要的小数点后几位
用字符串吗,
2、sscanf的用法,sprint的用法
sscanf(str,"%d",&n);
sprintf(str,"%d",n);

而且,可以以很多格式读入字符串

int main() {
    int n;
    double db;
    char str[100] = "2048:3.14,hello", str2[100];

    sscanf(str, "%d:%lf,%s", &n, &db, str2);
    printf("n = %d, db= %.2f, str2 = %s\n", n, db, str2);
    return 0;
}

int main() {
    int n = 12;
    double db = 3.1415;
    char str[100], str2[100] = "good";

    sprintf(str, "%d:%.2f,%s", n, db, str2);
    printf("str = %s\n", str);
    return 0;
}

*/

#include 

int main()
{
#include 
#include 
#include 
    using namespace std;
    int main() {
        int n, cnt = 0;
        char a[50], b[50];
        double temp, sum = 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 j = 0; j < strlen(a); j++)
                if (a[j] != b[j]) 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;
    }
}

你可能感兴趣的:(1054 求平均值 (20分))