PAT 乙级 1054 求平均值

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/a845717607/article/details/86220451

1054 求平均值 (20 point(s))

本题的基本要求非常简单:给定 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

经验总结:

这一题.....我感觉还行,前两遍手残调用错了函数编译错误,改好之后就通过了,这一题,可能也是不难,主要是注意的点比较多,要完全的不遗漏才能做到AC。
首先,对于非法输入的判断,有这么几个限制:
1,首先得是一个实数,(就是说字符串里面除了一个小数点,顶多还有一个负号,其余的必须全是数字)
2,这个数要在[-1000  ,1000] 以内(取绝对值进行判断)
3,这个数的小数位最多有两位
(这里要基于选正确的思想,而不是排错误的思想,因为你也不知道它会输入哪些非法的字符)
还有,对于输出格式也有三种限制
1,若合法数据个数为0   输出  The average of 0 numbers is Undefined
2,若合法数据个数为1   输出  The average of 1 number is Y(Y为输入)
3,若不满足以上两个     输出  The average of X numbers is Y(X,Y均为输入)

AC代码

#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
double fabs(double a)
{
	return a>0?a:-a;
}
bool judge(char str[],double &temp)
{
	int pot=0;
	if(str[0]!='-'&&!isdigit(str[0])&&str[0]!='.')
		return false;
	if(str[0]=='.')
		pot=1;
	int k=0;
	for(int i=1;str[i]!='\0';++i)
	{
		if(pot==1&&str[i]=='.')
			return false;
		if(str[i]!='.'&&!isdigit(str[i]))
			return false;
		if(pot==1)
			++k;
		if(pot==0&&str[i]=='.')
			pot=1;
	}
	if(k>2)
		return false;
	sscanf(str,"%lf",&temp);
	if(fabs(temp)>1000)
		return false;
	return true;
}
int main()
{
	int n,D;
	double e,temp;
	char str[110];
	while(~scanf("%d",&n))
	{
		int count=0;
		double sum=0;
		for(int i=0;i<n;++i)
		{
			scanf("%s",str);
			if(judge(str,temp))
			{
				sum+=temp;
				++count;
			}
			else
			{
				printf("ERROR: %s is not a legal number\n",str);
			}
		}
		if(count==0)
			printf("The average of 0 numbers is Undefined\n");
		else if(count==1)
			printf("The average of 1 number is %.2f\n",sum/count);
		else
			printf("The average of %d numbers is %.2f\n",count,sum/count);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/a845717607/article/details/86220451
今日推荐