The basic requirement of this question is very simple: Given N real numbers, calculate their average value. But complex is that some input data may be illegal. A "legitimate" input is a real number in the interval [1000,1000] and is at most accurate to two decimal places. When you calculate the average, you can't count the illegal data.
Input format:
Input the first line to give a positive integer N (< 100). The next line gives N real numbers separated by a space.
Output format:
For each illegal input, ERROR: X is not a legal number, where X is the input. Finally, The average of K numbers is Y, where K is the number of legitimate inputs and Y is their average value, accurate to two decimal places. If the average cannot be calculated, replace Y with Undefined. If K is 1, The average of 1 number is Y.
Input 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 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
Input Sample 2:
2 aaa -9999
Output Sample 2:
ERROR: aaa is not a legal number ERROR: -9999 is not a legal number The average of 0 numbers is Undefined
#include<stdio.h> #include<stdlib.h> int main() { int N = 0; scanf("%d",&N); char str[100] = {}; //Original string char dest[100] = {}; //Keep two decimal strings double num = 0; int flag = 0; //Is the record illegal? double Y = 0; int K = 0; for(int i = 0 ; i < N ; i++) { flag = 0; scanf("%s",str); sscanf(str,"%lf",&num); sprintf(dest,"%.2f",num); for(int i = 0 ;'\0' != str[i];i++) { if(str[i] != dest[i]) { flag = 1; break; } } if(1 == flag || num < -1000 || num > 1000) printf("ERROR: %s is not a legal number\n",str); else { Y += num; K++; } } if(0 == K) printf("The average of 0 numbers is Undefined\n"); else if(1 == K) printf("The average of 1 number is %.2f\n",Y); else printf("The average of %d numbers is %.2lf\n",K,Y/K); return 0; }