Skip to content

Latest commit

 

History

History
87 lines (78 loc) · 1.61 KB

1108.md

File metadata and controls

87 lines (78 loc) · 1.61 KB

1108

image.png

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
const int MAX_N = 1e2 + 5;

bool check(string s) {
	int num = 0;
	for (int i = 0; i < s.size(); i++) {
		if (!(s[i] >= '0' && s[i] <= '9') && s[i] != '.' && s[i] != '-') {
			return false;
		}
		if (s[i] == '.') {
			num++;
			if (num > 1) {
				return false;
			}
		}
	}
	if (find(s.begin(), s.end(), '.') - s.begin() + 2 < s.size() - 1) {
		return false;
	}
	if (stod(s) > 1000 || stod(s) < -1000) {
		return false;
	}
	return true;
}

int main() {
	int N;
	cin >> N;
	int num = 0;
	double sum = 0.0;
	for (int n = 0; n < N; n++) {
		string s;
		cin >> s;
		if (check(s)) {
			num++;
			sum += stod(s);
		}
		else {
			cout << "ERROR: " << s << " is not a legal number" << endl;
		}
	}
	if (num == 0) {
		cout << "The average of 0 numbers is Undefined" << endl;
	}
	else if (num == 1) {
		printf("The average of 1 number is %.2f\n", sum);
	}
	else {
		printf("The average of %d numbers is %.2f\n", num, sum / num);
	}
	return 0;
}

/*
Sample Input 1:
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35
Sample Output 1:
ERROR: aaa is not a legal number
ERROR: 9999 is not a legal number
ERROR: 2.3.4 is not a legal number
ERROR: 7.123 is not a legal number
The average of 3 numbers is 1.38
Sample Input 2:
2
aaa -9999
Sample Output 2:
ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefined
*/

References