1108 Finding Average (20分)

本文介绍了一种算法,用于验证输入字符串是否为合法数字,并计算这些数字的平均值。算法首先检查数字的有效性,包括小数点的正确使用、有效位数和数值范围,然后计算所有合法数字的平均值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
xx.也是合法数字…

#include<iostream>
#include<string>
#include<cctype>
#include<cmath>
using namespace std;
int main() {
	int n;
	cin >> n;
	double sum = 0;
	int count = 0;
	for (int i = 0;i < n;i++) {
		string temp;
		cin >> temp;
		int decimalPlace = -1;
		bool legal = true;
		for (int j = 0;j < temp.length();j++) {
			if (j == 0 && temp[j] == '-' && temp.length() > 1) {
				continue;
			}
			if (temp[j] != '.' && !isdigit(temp[j])) {
				legal = false;
				break;
			}
			else if (temp[j] == '.') {              //xx.也是合法数字??
				if (decimalPlace != -1 || j == 0) {
					legal = false;
					break;
				}
				else decimalPlace = j;
			}
		}
		int accuracy = 0;
		if (decimalPlace != -1) {
			accuracy = temp.length() - decimalPlace - 1;
		}
		if (!legal || decimalPlace != -1 && accuracy > 2 || temp.length() - accuracy > 6 || abs(stod(temp)) > 1000) {
			cout << "ERROR: " << temp << " is not a legal number" << endl;
		}
		else {
			sum += stod(temp);
			count++;
		}
	}
	if (count == 1) {
		printf("The average of %d number is ", count);
	}
	else printf("The average of %d numbers is ", count);
	if (count > 0) {
		printf("%.2lf", sum / count);
	}
	else printf("Undefined");
}

二刷:
不逐个判断不合法的情况,而是只允许合法的情况通过,避免了要逐一排除各种不合法的情况。

#include<iostream>
#include<string>
#include<cctype>
using namespace std;
int main() {
	int n;
	cin >> n;
	double sum = 0;
	int count = 0;
	for (int i = 0; i < n; i++) {
		string s;
		cin >> s;
		bool isLegal = true;
		int pointIndex = s.find('.');
		if (pointIndex != -1 && s.length() - pointIndex - 1 > 2) {
			isLegal = false;
		}
		bool hasDigit = false;
		for (int j = 0; j < s.length(); j++) {
			//如果输入合法,则继续判断,而不逐个排除不合法输入
			if (j == 0 && s[j] == '-') {
				continue;
			}
			if (s[j] == '.' && j == pointIndex) {
				continue;
			}
			if (isdigit(s[j])) {
				hasDigit = true;
				continue;
			}
			isLegal = false;
			break;
		}
		if (!hasDigit) {	//避免 -. 和 -
			isLegal = false;
		}
		if (isLegal) {
			double num = stod(s);
			if (num >= -1000 && num <= 1000) {
				sum += num;
				++count;
			}
			else {
				isLegal = false;
			}
		}
		if (!isLegal) {
			printf("ERROR: %s is not a legal number\n", s.c_str());
		}
	}
	if (count == 0) {
		printf("The average of 0 numbers is Undefined\n");
	}
	else if (count == 1) {
		printf("The average of 1 number is %.2lf", sum / count);
	}
	else {
		printf("The average of %d numbers is %.2lf\n", count, sum / count);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值