1108. Finding Average (20)
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
题意:给你n个数,问这n个数是否合法,合法的数范围在[-1000,1000],且不含有除阿拉伯数字,小数点和‘-’的字符,小数点最多出现一次,小数点后最多两位,并输出合法的数的平均值
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
using namespace std;
#define LL long long
const int INF = 0x3f3f3f3f;
int n;
char ch[100];
int main()
{
while(~scanf("%d",&n))
{
double ans=0;
int cnt=0;
for(int i=0;i<n;i++)
{
scanf("%s",ch);
int len=strlen(ch);
int kk=ch[0]=='-'?-1:1,flag=1;
double temp=0,k=0;
for(int j=ch[0]=='-'?1:0;j<len;j++)
{
if(ch[j]=='.'&&!k) k=0.1;
else if(ch[j]=='.'&&k) {flag=0;break;}
else if(!k&&ch[j]>='0'&&ch[j]<='9') temp=temp*10+ch[j]-'0';
else if(k&&ch[j]>='0'&&ch[j]<='9') temp=temp+k*(ch[j]-'0'),k/=10;
else {flag=0;break;}
}
temp*=kk;
if(temp<-1000||temp>1000||(k<0.001&&k)) flag=0;
if(flag)
{
cnt++;
ans+=temp;
}
else printf("ERROR: %s is not a legal number\n",ch);
}
if(cnt>1) printf("The average of %d numbers is %.2lf\n",cnt,ans/cnt);
else if(cnt==1) printf("The average of 1 number is %.2lf\n",ans);
else printf("The average of 0 numbers is Undefined\n");
}
return 0;
}