PAT 甲级 1108 Finding Average (20分)
Posted caiyishuai
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT 甲级 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 [−] 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 (≤). 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.35
Sample 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.38
Sample Input 2:
2
aaa -9999
Sample Output 2:
ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefined
题意:
给出一组数据,判断输出是不是合法数字(精度不超过小数点后两位,范围【-1000,1000】),有合法数据还要累加算出average;不存在合法数据输出The average of 0 numbers is Undefined
题解:
第一发没过原因是number和numbers没有看清楚。k=0,1,>1要分开讨论。
注意细节:详见代码注释。
AC代码:
#include<bits/stdc++.h> using namespace std; int main(){ int n; int k=0; double sum=0; string a; cin>>n; for(int i=1;i<=n;i++){ cin>>a; double add=0; int l=a.length(); int fu=0; int p=-1; int legal=1; for(int i=0;i<l;i++){ if(i==0){ if(a[i]==‘-‘){ fu=1; continue; } } if(a[i]==‘.‘){ if(p!=-1){//记录小数点位置 legal=0; break; }else{ p=i; if(l-i>3){//小数点后有三位了,不合法 legal=0; break; } } }else if(a[i]>=‘0‘&&a[i]<=‘9‘){ if(p!=-1&&i-p==1){//小数点后两位特殊处理 add=add+(a[i]-‘0‘)*0.1; }else if(p!=-1&&i-p==2){ add=add+(a[i]-‘0‘)*0.01; }else{ add=add*10+a[i]-‘0‘; } if(abs(add)>1000){//数过大或过小 legal=0; break; } }else{ legal=0; break; } } if(!legal){ printf("ERROR: %s is not a legal number ",a.c_str()); }else{ if(fu==1) add=0-add;//负数 sum+=add; k++; } } if(k==0){ printf("The average of 0 numbers is Undefined"); }else if(k==1){ printf("The average of %d number is %.2lf",k,sum/k); }else{ printf("The average of %d numbers is %.2lf",k,sum/k); } return 0; }
以上是关于PAT 甲级 1108 Finding Average (20分)的主要内容,如果未能解决你的问题,请参考以下文章
pat 1108 Finding Average(20 分)
PAT甲题题解-1108. Finding Average (20)-字符串处理