Fork me on GitHub

PAT 1054 求平均值

题目:

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

思路:我是一步一步的判断这个字符串是不是全是数字,小数点是不是只有一个,小数位是不是只有两位和转换过来的数是否越界这几个条件来筛选,在筛选过程中逐步输出不符合的,最后累加符合的数。

坑点:这里有一个坑点是只有一个符合的时候要单独拎出来,因为输出的number是不加s的,其余的情况都为numbers。

#include<iostream>
#include<string>
#include<vector>
#include<iomanip>
#include<math.h>
using namespace std;
int main()
{
	int N = 0,K=0,count=0; cin >> N;
	vector<string>str;
	double average = 0.0;
	for (int i = 0; i < N; i++)
	{
		string temp;
		cin >> temp;
		str.push_back(temp);
	}
	for (int i = 0; i < str.size(); i++)
	{
		int flag = 1, step = 1,j=0;
		double temp = 0.0;
		if (str[i][0] != '-' &&(str[i][0] < '0' || str[i][0]>'9'))//判断字符串第一个字符是不是‘-’或者数字,不是的直接输出错误
		{
			cout << "ERROR: "<<str[i]<<" is not a legal number" << endl;
			continue;
		}
		if (str[i][0] == '-')//如果是负数,字符串从下标1开始循环判断
				j = 1;
			while (str[i][j] != '.'&&j<str[i].size())//循环至小数点的位置结束,同时将字符转换成对应的数字
			{
				temp = temp * 10 + (double)(str[i][j] - '0');
				++j;
			}
			++j;//跳过第一个小数点
			for (int k = j; k < str[i].size(); k++)//循环判断第一个小数点后是否还有小数点,如果有,那么这个字符串不符合要求
			{
				if (str[i][k] == '.')
				{
					flag = 0;
				}
			}
			if (flag)//前面要求都符合
			{
				while (j < str[i].size())//如果有小数位,将小数位加上
				{
					temp = temp + double(str[i][j]- '0') / (pow(10, step));
					++step;
					++j;
				}
				if (temp >= -1000 && temp <= 1000&&step<=3)//判断该数小数位是不是两位并且有没有越界
				{
					K++;//k用来累加符合的数
					if (str[i][0] == '-')temp = -temp;
					average = average + temp;//求和
				}
				else cout << "ERROR: " << str[i] << " is not a legal number" << endl;
			}
			else 	cout << "ERROR: " << str[i] << " is not a legal number" << endl;
	}
	if(K==1)//K为1的情况单独拎出来,因为只有一个符合的时候,number是不加s的
		cout<<"The average of "<<1<<" number is "<<fixed<<setprecision(2)<<average<<endl;
	else if(K==0)//其余的情况为numbers
		cout << "The average of " << 0 << " numbers is Undefined" << endl;
	else cout << "The average of " << K << " numbers is " << fixed<<setprecision(2)<< average/K<<endl;
	return 0;
}

 

posted @ 2020-03-31 09:18  GOGP_nikto  阅读(139)  评论(0编辑  收藏  举报