PAT 1054 求平均值 (字符串+精度(估计也只有我))

#include <iostream>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <string>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
	int n;
	while (cin>>n) 
	{
		char s[50];
		int num = 0;
		double sum = 0;
		for (int i = 0; i < n; i++)
		{
			cin >> s;
			int len = strlen(s);
			int flag = 1;
			int cnt = 0;
			for (int j = 0; j < len; j++)
			{
				if ('0' <= s[j] && s[j] <= '9' || (s[j]=='-' && j==0))
					continue;
				else if (s[j] == '.')
				{
					cnt++;
					int point = strlen(s + j + 1);
					if (cnt > 1 || point>2)
					{
						flag = 0;
						break;
					}
				}
				else
				{
					flag = 0;
					break;
				}
			}
			if (!flag)
			{
				printf("ERROR: %s is not a legal number\n", s);
			}
			else
			{
				double e;
				sscanf(s, "%lf", &e);
				if(e<-1000 || e>1000)
					printf("ERROR: %s is not a legal number\n", s);
				else
				{
					num++;
					sum += e;
				}
			}
		}
		if (num == 0)
			printf("The average of 0 numbers is Undefined\n");
		else if (num == 1)
			printf("The average of 1 number is %.2lf\n", sum);
		else
			printf("The average of %d numbers is %.2lf\n", num, sum / num);
	}
	return 0;
}

题目是输入n个实数,我觉得也只能是字符串了,浮点型aaa这样的也输不进去……

合法的如下

1. 【-1000,1000】

2.小数位在二位内的。

最后一个案例过不了

我的过程是 先把字符串遍历一遍,遇到了1.不是0-9的字符 2.不是小数点 3. 不是负号 就直接退出。剩下的一定是一个浮点型数字,那么可以直接转换为浮点型数字判断大小和精度了,前一个条件好判断,后一个我采取的方法是*100然后转换为int再看是否与刚乘100的浮点数比较,当时我被我的聪明才智惊到了,然鹅一直错就是因为这点小聪明,如果是1.000,这样的方法是错的!

所以我们检测到小数点就判断一下小数点后有多少位数,如果比2大,那么就是不合法的。

另外我还看到一种特别秀的写法,那个是真的牛。我想到了精度,却没想到字符串,真是……

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值