1. 程式人生 > 其它 >1054 求平均值 (20 分)

1054 求平均值 (20 分)

技術標籤:PAT筆記字串演算法c++

1054 求平均值 (20 分)

本題的基本要求非常簡單:給定 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. 第一位只能是數和符號
  2. 只能由0-9.構成
  3. 小數點只能出現一次且小數點之後只能有兩位小數
  4. 數的取值範圍在[-1000,1000],越界不能要

可以直接呼叫庫函式stof(a),把string轉化成float格式,更多轉換操作見另一篇文章

輸出的時候注意格式,仔細審題,當只有一個輸出的時候時number單數而不是numbers,不然會錯一個。輸出的時候保留兩位小數,通過.2f即可實現


AC例程
#include<iostream>
#include<stdlib.h>
#include<stdio.h> #include<string.h> #include<math.h> #include<algorithm> #include<vector> #include<map> #include<queue> #include<sstream> using namespace std; int judge(string a) { int count =0; if(a.length()>8)return 2; if(a[0]=='-'||(a[0]>='0'&&a[0]<='9')){ for(int i=1;i<a.length();i++) { if((a[i]<'0'&&a[i]!='.')||a[i]>'9')return 3; if(a[i]=='.') { if(count==0){ count++; if(a.length()-i-1>2) return 4; } else 5; } } }else return 6; return 1; } int main(){ #ifdef ONLINE_JUDGE #else freopen("in.txt","r",stdin); #endif int n; string a; while(cin>>n){ int count=0; float sum=0; while(n--) { a="";cin>>a; if(judge(a)==1) { if(stod(a)<=1000&&stod(a)>=-1000) {count++; sum+=stod(a); }else cout<<"ERROR: "<<a<<" is not a legal number"<<endl; }else { cout<<"ERROR: "<<a<<" is not a legal number"<<endl; } } if (count>1){ cout<<"The average of ";cout<<count; cout<<" numbers is ";printf("%.2f\n",sum/count); } else if(count==1) { cout<<"The average of ";cout<<count; cout<<" number is ";printf("%.2f\n",sum/count); } else cout<<"The average of 0 numbers is Undefined"<<endl; } return 0; }