本題的基本要求非常簡單:給定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
1 #include<iostream>
2 #include<cstdlib>
3 #include<cstdio>
4 #include<cstring>
5 using namespace std;
6 int main(){
7 char *num[105];
8 int N,count=0;
9 double average=0;
10 cin>>N;
11 for(int i=0;i<N;i++){
12 bool isNumber=true; //判斷是否為合法數字
13 int point=0; //監視小數點的個數
14 int point_=0; //監視小數點之後的位數
15 num[i] = (char *)malloc(10*sizeof(char)); //申請空間
16 cin>>num[i];
17 int len=strlen(num[i]);
18 double temp=atof(num[i]);//將字符串轉換成數字,具體用法自行百度
19 if(temp<-1000||temp>1000) isNumber=false;
20 for(int j=0;j<len;j++){ //對每一個元素的各個字符進行判斷
21 if(point==1) point_++;
22 if(num[i][j]=='-'&&j!=0){//如果含有-,則-只有一個且在第一位
23 isNumber=false;
24 break;
25 }
26 if(num[i][j]!='.'){
27 if((num[i][j]<'0'||num[i][j]>'9')&&(num[i][j]!='-')){
28 isNumber=false;
29 break;
30 }
31 }else { //如果是小數點
32 point++;
33 }
34 if(point_>2||point>1){//如果小數點大於一個或者小數位數多余2
35 isNumber=false;
36 break;
37 }
38 }
39 if(!isNumber)
40 cout<<"ERROR: "<<num[i]<<" is not a legal number"<<endl;
41 else {
42 count++;
43 average+=temp;
44 }
45 }
46 if(count==1)
47 printf("The average of 1 number is %.2lf",average);
48 else if(count==0)
49 printf("The average of 0 numbers is Undefined");
50 else
51 printf("The average of %d numbers is %.2lf",count,average/count);
52 return 0;
53 }