1054. Average time limit ms
Memory Limit 65536 KB
Code length limit 8000 B
Standard author CHEN, Yue
The basic requirements of this subject are very simple: given n real numbers, the average of them is computed. But the complication is that some of the input data may be illegal. A "valid" input is a real number within the [ -1000,1000] interval and is at most accurate to 2 digits after the decimal point. When you calculate the average, you can't count the illegal data.
Input Format:
Enter the first row to give the positive integer n (<=100). The next line gives N a real number, separated by a space between the digits.
output Format:
For each illegal input, output "error:x is not a legal number" on one line, where X is input. Finally, the result is output in one line: "The average of K numbers is Y", where K is the number of valid inputs, Y is their average, accurate to 2 digits after the decimal point. If the average is not calculated, replace Y with "Undefined". If k is 1, the output "the average of 1 is Y". Enter Sample 1:
7
5-3.2 AAA 9999 2.3.4 7.123 2.35
Output Sample 1:
ERROR:AAA is not a legal number error:9999 are not a legal number error:2.3.4 are not
a legal number
Error:7 .123 is isn't a legal number the
average of 3 numbers is 1.38
Enter Sample 2:
2
aaa-9999
Output Sample 2:
ERROR:AAA is isn't a legal number
ERROR: -9999 is isn't a legal number the
average of 0 numbers is Undefined
#include <stdio.h> #include <iostream> #include <string> #include <algorithm> using namespace
Std
BOOL IsDigit (string str) {bool Firstpoint = true;
for (int i = 0; i < str.length (); i + +) {if ((str[i] = = ' + ' | |-str[i] = = ') && i = = 0) continue;
if (Str[i] >= ' 0 ' && str[i] <= ' 9 ') continue;
if (str[i] = = '. ' && firstpoint) {firstpoint = false;
if (I >= str.length ()-3) continue;
return false;
return true;
float stringtofloat (string str) {float sum = 0.0;
bool Firstpoint = true;
for (int i = 0; i < str.length (); i + +) {if ((str[i] = = ' + ' | |-str[i] = = ') && i = = 0) continue;
if (Str[i] >= ' 0 ' && str[i] <= ' 9 ') sum = sum * + (str[i)-' 0 ');
if (str[i] = = '. ')
{if (i = = Str.length ()-3) sum = sum + (str[i+1]-' 0 ') *0.1 + (str[i+2]-' 0 ') *0.01;
if (i = = Str.length ()-2) sum = sum + (str[i+1]-' 0 ') *0.1;
Break } return str[0] = = '-' ?
-1*sum:sum;
int main () {//freopen ("D://input.txt", "R", stdin);
int n;
scanf ("%d", &n);
float totalSum = 0.0;
int count = 0;
string input;
for (int i = 0; i < n; i + +) {cin>>input; if (isdigit (input)) {if (stringtofloat (input) >= -1000 && stringtofloat (input) <= 1000) {TOTALSU
M + + stringtofloat (input);
Count + +;
Else cout<< "ERROR:" <<input<< "is not a legal number" <<endl;
Else cout<< "ERROR:" <<input<< "is not a legal number" <<endl;
if (Count > 1) printf ("The average of%d numbers is%.2f\n", count, Totalsum/count);
else if (count = = 1) printf ("The average of%d number is%.2f\n", count, Totalsum/count);
else printf ("The average of 0 numbers is undefined\n");
return 0; }