A1108 Finding Average [字符串]

在这里插入图片描述

#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<cstring>
#include<cstdio>	
using namespace std;
int main() {
	int n;
	cin >> n;
	string s[101];
	vector<string>v;
	for (int i = 0; i < n; i++)
	{
		cin >> s[i];
	}
	bool flag,flag1=false; int dem;
	for (int i = 0; i < n; i++)
	{
		flag = false;
		dem = 0;
		for (int j = 0; j < s[i].length(); j++)
		{
			if (j == 0 && s[i][j] == '-')
			{
				j++;
				flag1 = true;
			}
			if (s[i][j] == '.')
			{
				dem++;
				if (flag1)
				{
					cout << "ERROR: " << s[i] << " is not a legal number\n";
					break;
				}
				if (j == 0 || dem > 1 || s[i].length() - j > 3)
				{
					flag = true;
					cout << "ERROR: " << s[i] << " is not a legal number\n";
					break;
				}
				flag1 = false;
			}
			else if (isdigit(s[i][j]))
			{
				flag1 = false;
			}
			else
			{
				flag = true;
				flag1 = false;
				cout << "ERROR: " << s[i] << " is not a legal number\n";
				break;
			}
		}
		if (flag == false&&flag1==false)
		{
			if (stof(s[i]) < -1000 || stof(s[i]) > 1000)
			{
				cout << "ERROR: " << s[i] << " is not a legal number\n";
			}
			else
			{
				v.push_back(s[i]);
			}
		}
	}
	if (v.size() == 0)
	{
		printf("The average of 0 numbers is Undefined\n");
	}
	else if(v.size() == 1){
		printf("The average of %d number is %.2f\n",v.size(),stof(v[0]));
	}else{
		double sum = 0;
		for(int i = 0;i < v.size();i++){
			sum+=stof(v[i]);
		}
		printf("The average of %d numbers is %.2f\n",v.size(),sum/v.size());
	}
	return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值