1108 Finding Average(IO格式处理)

注意使用stoi,stof,isdigit

#include<bits/stdc++.h>
#include<unordered_set>
#define f(i,a,b) for(int i=a;i<=b;++i)
#define fd(i,a,b) for(int i=a;i>=b;--i)
#define debug(x) cerr<<#x<<": "<<x<<endl;
using namespace std;
typedef long long ll;
bool check(string s, double &x) {
	int id = 0;
	if (s[id] == '-')id++;
	int fg = 0, count = 0;
	int sz = s.size() - 1;
	while (id <= sz) {
		if (s[id] == '.'&&fg)return false;//two p
		if (s[id] == '.')fg++;
		else if (!isdigit(s[id]))return false;
		else {
			if (fg)count++;
		}
		id++;
	}
	if (count > 2)return false;
	x = stof(s);
	if (x < -1000 || x>1000)return false;
	return true;
}
int main()
{
#ifndef ONLINE_JUDGE
	freopen("in.txt", "r", stdin);
#endif
	//io格式处理:stoi,stof
	int n;cin >> n;
	double sum = 0;
	int num = 0;
	f(i, 1, n) {
		double x;
		string s;cin >> s;
		if (check(s, x))sum += x, num++;
		else {
			cout << "ERROR: ";
			cout << s;
			cout << " is not a legal number" << endl;
		}
	}
	if (num) {
		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);
		}
	}
	else {
		printf("The average of 0 numbers is Undefined\n");
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值