問題很簡單,但是要判斷的東西很多:
本題的基本要求非常簡單:給定 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
注意 K == 1輸出的是 number,而大於1時則輸出的是 numbers 。
頭文件<ctype.h>中定義了對字符串進行判斷的函數,包括:
掌握isdigit(ch), islower(ch), isupper(ch), tolower(ch), toupper(ch)即可。
#include<bits/stdc++.h>
#include<cstdlib>
using namespace std;
int main()
{
char ch = 'A';
if(isupper(ch))
cout << ch << "是大寫的" << endl;
ch = tolower(ch);
if(islower(ch))
cout << ch << "是小寫的" << endl;
return 0;
}
運行截圖爲:
<stdlib.h>或者<cstdlib>中的atof(char str[])可以將字符串轉換爲浮點型。此外還有atoi()函數以及atol()函數。
其餘的判斷細節都在代碼中體現:
#include<bits/stdc++.h>
using namespace std;
char str[101][101];
int N;
bool judge(char str[])
{
int i = 0;
if(str[0] == '-')
i++;
for(; str[i] && str[i] != '.'; i++)
{
if(!isdigit(str[i]))
return false;
}
if(str[i] == '.')
{
for(int j = i + 1;str[j]; j++)
{
if(!isdigit(str[j]) || j - i > 2)
return false;
}
}
double num = fabs(atof(str));
if(num > 1000)
return false;
else
return true;
}
void V()
{
int K = 0;
double total = 0;
for(int i = 0; i < N; i++)
{
if(!judge(str[i]))
printf("ERROR: %s is not a legal number\n", str[i]);
else
{
K++;
total += atof(str[i]);
}
}
if(K == 0)
printf("The average of 0 numbers is Undefined\n");
else if(K == 1)
printf("The average of 1 number is %.2f\n", total);
else
printf("The average of %d numbers is %.2f\n", K, total/K);
}
int main()
{
scanf("%d", &N);
for(int i = 0; i < N; i++)
{
scanf("%s", str[i]);
}
V();
return 0;
}
參考: