PAT 1108

简单模拟,求合法的数的平均值,坑点在3. 2.这样的数也是合法的,还有就是输出的时候number注意单复数,0是复数,代码略复杂仅供参考

#include <iostream>
#include <string>
#include <cstring>
#include<algorithm>
#include<cmath>
#include <vector>
#include <map>
#include<stack>
#include<queue>
#include <stdio.h>
using namespace std;
#define MAX 500+5
#define INF 0x3f3f3f3f
struct NUMBER {
	string str;
	int flag=0;
	int w;
	int zf;
}d[MAX];
int main() { 
	int n, i, j, count=0;
	double ans = 0;
	double p=0;
	scanf("%d", &n);
	for (i = 0; i < n; i++) {
		cin >> d[i].str;
	}
	for (i = 0; i < n; i++) {
		int xsd = 0,ws=0,xsw=0,temp=0,zm=0;
		string::iterator   it;
		it = d[i].str.begin();
		if (*it == '-') {
			d[i].zf = 0;
			d[i].str.erase(it);
		}
		else {
			d[i].zf = 1;
		}
		for (j = 0; j < d[i].str.length(); j++) {
			if (d[i].str[j] >= '0'&&d[i].str[j] <= '9'&&!temp) {
				ws++;
			}
			else if (d[i].str[j] >= '0'&&d[i].str[j] <= '9' &&temp) {
				xsw++;
			}
			else if (d[i].str[j] == '.'&&xsd==0) {
				xsd++;
				d[i].w = j;
				temp = 1;
			}
			else if (d[i].str[j] == '.') {
				xsd++;
			}
			else if (d[i].str[j] >= 'a'&&d[i].str[j] <= 'z') {
				d[i].flag = 0;
				xsd =99;
				break;
			}
		}
		if (xsd == 0||xsd==1&&xsw==0) {
			int q=0, tmp=1;
			for (int k = d[i].str.length()-1; k >=0 ; k--) {
				if (d[i].str[k] == '.')
					continue;
				q += tmp*(d[i].str[k] - '0');
				tmp *= 10;
			}
			if (q >= 0 && q <= 1000 && d[i].zf) {
				ans += q;
				count++;
				d[i].flag = 1;
			}
			else if (q >= 0 && q <= 1000 && !d[i].zf) {
				ans -= q;
				count++;
				d[i].flag = 1;
			}
			else {
				d[i].flag = 0;
			}
		}
		else if (xsd == 1 && xsw <= 2 && xsw >= 1) {
			double q = 0,tmp=1;
			for (int k = d[i].w - 1; k >= 0; k--) {
				q += tmp*(d[i].str[k] - '0');
				tmp *= 10;
			}
			tmp = 0.1;
			for (int k = d[i].w + 1; k <d[i].str.length(); k++) {
				q += tmp*(d[i].str[k] - '0');
				tmp /= 10;
			}
			if (q >= 0.00 && q <= 1000.00&&d[i].zf) {
				ans += q;
				count++;
				d[i].flag = 1;
			}
			else if (q >= 0.00 && q <= 1000.00&&!d[i].zf) {
				ans -= q;
				count++;
				d[i].flag = 1;
			}
			else {
				d[i].flag = 0;
			}
		}
		else{
			d[i].flag = 0;
		}
	}
	for (i = 0; i < n; i++) {
		if (d[i].flag == 0&&d[i].zf) {
			cout << "ERROR: " << d[i].str << " is not a legal number" << endl;
		}
		else if (d[i].flag == 0 && !d[i].zf) {
			cout << "ERROR: -" << d[i].str << " is not a legal number" << endl;
		}
		
	}
	if (count > 1) {
		printf("The average of %d numbers is %.2lf\n", count, ans / count);
	}
	else if (count == 1) {
		printf("The average of 1 number is %.2lf\n",  ans);
	}
	else if (count == 0) {
		printf("The average of 0 numbers is Undefined\n");
	}
	
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值