The basic task is simple: given N real numbers, you are supposed to calculate their average. But what makes it complicated is that some of the input numbers might not be legal. A "legal" input is a real number in [-1000, 1000] and is accurate up to no more than 2 decimal places. When you calculate the average, those illegal numbers must not be counted in.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=100). Then N numbers are given in the next line, separated by one space.
Output Specification:
For each illegal input number, print in a line "ERROR: X is not a legal number" where X is the input. Then finally print in a line the result: "The average of K numbers is Y" where K is the number of legal inputs and Y is their average, accurate to 2 decimal places. In case the average cannot be calculated, output "Undefined" instead of Y. In case K is only 1, output "The average of 1 number is Y" instead.
Sample Input 1:7 5 -3.2 aaa 9999 2.3.4 7.123 2.35Sample Output 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.38Sample Input 2:
2 aaa -9999Sample Output 2:
ERROR: aaa is not a legal number ERROR: -9999 is not a legal number The average of 0 numbers is Undefined
20分值的PAT都是水题,几个if判断一下合不合法就可以了。
tip:第四组样例中有“123.”这样的数据,是合法的,判断为不合法就不通过。
#include <cstdio>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <cstdlib>
#include <climits>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define ll long long
const int MAXN = 100000 + 5;
const int MAXM = 100000 + 5;
const int INF = 0x7f7f7f7f;
template <class XSD> inline XSD f_min(XSD a, XSD b) { if (a > b) a = b; return a; }
template <class XSD> inline XSD f_max(XSD a, XSD b) { if (a < b) a = b; return a; }
int n, m;
int cnt;
char s[MAXN];
double sum;
bool Is_legal(){
int len=strlen(s), len0=len;
int op=(s[0]=='-');
for(int i=0; i<len; i++){
if((s[i]<'0' || s[i]>'9') && s[i]!='.' && s[i]!='-') return false;///不合法ASCII
if(s[i]=='-' && i) return false;///'-'首位
if(s[i]=='.'){///精确度
if(s[len] || len-i>3) return false;
len = i;
}
}
double inter=0, dot=0, ans;
for(int i=op; i<len; i++) inter = inter*10+(s[i]-'0');///整数
for(int i=len0-1; i>len; i--) dot = (dot+s[i]-'0')/10;///小数
ans = inter+dot;
if(ans>1000.0) return false;
else{
if(op) sum+=(-ans);
else sum+=ans;
//sum += (op?-1:1)*ans;
return true;
}
}
void Getdata(){
sum=0.0;
cnt=0;
for(int i=0; i<n; i++){
scanf("%s", s);
if(Is_legal()) cnt++;
else printf("ERROR: %s is not a legal number\n", s);
}
}
void Solve(){
if(!cnt) printf("The average of 0 numbers is Undefined\n");
else printf("The average of %d number%s is %.2f\n", cnt, cnt==1?"":"s", sum/cnt);
}
int main(){
while(~scanf("%d", &n)){
Getdata();
Solve();
}
return 0;
}