1. 程式人生 > >PAT-B 1054. 求平均值

PAT-B 1054. 求平均值

題目內容:

本題的基本要求非常簡單:給定N個實數,計算它們的平均值。但複雜的是有些輸入資料可能是非法的。一個“合法”的輸入是[-1000,1000]區間內的實數,並且最多精確到小數點後2位。當你計算平均值的時候,不能把那些非法的資料算在內。

輸入格式:

輸入第一行給出正整數N(<=100)。隨後一行給出N個正整數,數字間以一個空格分隔。

輸出格式:

對每個非法輸入,在一行中輸出“ERROR: X is not a legal number”,其中X是輸入。最後在一行中輸出結果:“The average of K numbers is Y”,其中K是合法輸入的個數,Y是它們的平均值,精確到小數點後2位。如果平均值無法計算,則用“Undefined”替換Y。如果K為1,則輸出“The average of 1 number is Y”。

輸入樣例1:

7
5 -3.2 aaa 9999 2.3.4 7.123 2.35

輸出樣例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

輸入樣例2:

2
aaa -9999

輸出樣例2:

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

思路分析:

就想題目說的,題目本身邏輯很簡單,所以寫了一個判斷讀入的數字是否有效的函式。主函式中,讀入資料,判斷是否有效,累加,並完成求平均值的任務。

程式碼:

#include <stdio.h>
#include <stdlib.h>

int effect(char a[]) // 判斷數字是否合法
{
    int dot = 0, i = 0, n1 = 0, n2 = 0;
    if (a[0] == '-') i = 1; // 如果開頭有負號跳過
    for (; a[i] != '\0'; i++) {
        if ((a[i] < 48
|| 57 < a[i]) && a[i] != '.') return 0; // 存在數字和'.'以外的字元則不合法 if (dot == 1 && a[i] == '.') return 0; // dot為1表示出現過'.',再出現的'.'導致數字不合法 if (dot > 0) n1++; // n1表示小數部分位數 if (a[i] == '.') dot = 1; // 出現了'.'就將dot標記置為1 if (dot == 0) n2++; // n2表示整數部分位數 } if (n1 > 2) return 0; // 小數部分多於兩位不合法 if (atof(a) < -1000.0 || atof(a) > 1000.0) return 0; // atof將字串轉換為浮點數,並判斷範圍是否合法 return 1; } int main() { int n, cnt = 0; double sum = 0.0f, v; char tmp[101] = {0}; scanf("%d", &n); // 讀入資料個數n for (int i = 0; i < n; i++) { // 迴圈讀取資料的同時,判斷是否合法,並輸出錯誤資訊 scanf("%s", tmp); if (effect(tmp)) sum += atof(tmp), cnt++; else printf("ERROR: %s is not a legal number\n", tmp); // 輸出錯誤資訊 } v = sum / cnt; printf("The average of %d number", cnt); if (cnt == 0) printf("s is Undefined\n"); // 根據有效資料個數分類輸出平均數 if (cnt == 1) printf(" is %.2f\n", v); if (cnt >= 2) printf("s is %.2f\n", v); return 0; }