PAT 乙級 1054 求平均值
阿新 • • 發佈:2019-01-11
1054 求平均值 (20 point(s))
本題的基本要求非常簡單:給定 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
經驗總結:
這一題.....我感覺還行,前兩遍手殘呼叫錯了函式編譯錯誤,改好之後就通過了,這一題,可能也是不難,主要是注意的點比較多,要完全的不遺漏才能做到AC。
首先,對於非法輸入的判斷,有這麼幾個限制:
1,首先得是一個實數,(就是說字串裡面除了一個小數點,頂多還有一個負號,其餘的必須全是數字)
2,這個數要在[-1000 ,1000] 以內(取絕對值進行判斷)
3,這個數的小數位最多有兩位
(這裡要基於選正確的思想,而不是排錯誤的思想,因為你也不知道它會輸入哪些非法的字元)
還有,對於輸出格式也有三種限制
1,若合法資料個數為0 輸出 The average of 0 numbers is Undefined
2,若合法資料個數為1 輸出 The average of 1 number is Y(Y為輸入)
3,若不滿足以上兩個 輸出 The average of X numbers is Y(X,Y均為輸入)
AC程式碼
#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
double fabs(double a)
{
return a>0?a:-a;
}
bool judge(char str[],double &temp)
{
int pot=0;
if(str[0]!='-'&&!isdigit(str[0])&&str[0]!='.')
return false;
if(str[0]=='.')
pot=1;
int k=0;
for(int i=1;str[i]!='\0';++i)
{
if(pot==1&&str[i]=='.')
return false;
if(str[i]!='.'&&!isdigit(str[i]))
return false;
if(pot==1)
++k;
if(pot==0&&str[i]=='.')
pot=1;
}
if(k>2)
return false;
sscanf(str,"%lf",&temp);
if(fabs(temp)>1000)
return false;
return true;
}
int main()
{
int n,D;
double e,temp;
char str[110];
while(~scanf("%d",&n))
{
int count=0;
double sum=0;
for(int i=0;i<n;++i)
{
scanf("%s",str);
if(judge(str,temp))
{
sum+=temp;
++count;
}
else
{
printf("ERROR: %s is not a legal number\n",str);
}
}
if(count==0)
printf("The average of 0 numbers is Undefined\n");
else if(count==1)
printf("The average of 1 number is %.2f\n",sum/count);
else
printf("The average of %d numbers is %.2f\n",count,sum/count);
}
return 0;
}