题目链接https://pintia.cn/problem-sets/994805342720868352/problems/994805360777347072
题目大意:给出N个数字,求平均数。其中可能有非法的数字,要剔除。要求数字绝对值小于等于1000且精度最多两位。
所以主要就是判断是否合法,把所有非法都剔除即可。【负号只能出现在开头】【小数点最多一个】【小数点后最多再出现两位】等等条件判断了即可。
输出时注意合法数字个数为0或者1的情况。
完整代码
#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#include <set>using namespace std;bool isLegal(string num) {
int dot_num = 0;int dot_pos = -1;for (int i = 0; i < num.size(); i++) {
if (num[i] == '.') {
dot_pos = i;dot_num++;if (dot_num > 1)return false;}else if (num[i] >= '0' && num[i] <= '9'){
if (dot_pos > 0 && i - dot_pos > 2)return false;}else if (num[i] == '-'){
if (i != 0)return false;}elsereturn false;}double number = stof(num);if (abs(number) > 1000)return false;return true;
}int main() {
int N;int cnt = 0;double sum = 0.0;string num;scanf("%d", &N);for (int i = 0; i < N; i++) {
cin>>num;if (isLegal(num) == true) {
sum += stof(num);cnt++;}elsecout<< "ERROR: " << num << " is not a legal number"<<endl;}if (cnt > 1)printf("The average of %d numbers is %.2f", cnt, sum/(1.0*cnt));else if (cnt == 1)printf("The average of 1 number is %.2f", sum);elseprintf("The average of 0 numbers is Undefined");return 0;
}