1054. Averaging (20)
The basic requirement of the subject is very simple: given n real numbers, calculate their average. But the complex is that some of the input data may be illegal. A "valid" input is a real number within the [ -1000,1000] interval and is up to 2 digits after the decimal point. When you calculate the average, you can't count the illegal data.
Input format:
Enter the first line to give the positive integer n (<=100). The next line gives n positive integers, separated by a space between the numbers.
Output format:
For each illegal input, output "error:x is not a legal number" in a row, where X is the input. Finally, the result is output in a row: "The average of K numbers is Y", where K is the number of legal inputs, Y is their average value, accurate to 2 digits after the decimal point. If the average cannot be calculated, replace Y with "Undefined". If k is 1, then output "The average of 1 number is Y".
Input Sample 1:
75-3.2 AAA 9999 2.3.4 7.123 2.35
Output Example 1:
ERROR:AAA is not a legal numbererror:9999 are not a legal numbererror:2.3.4 are not a legal numbererror:7.123 are not a l Egal numberthe average of 3 numbers is 1.38
Input Sample 2:
2aaa-9999
Output Example 2:
ERROR:AAA is not a legal numbererror: -9999 are not a legal numberthe average of 0 numbers are Undefined
1#include <iostream>2#include <cstdlib>3#include <cstdio>4#include <cstring>5 using namespacestd;6 intMain () {7 Char*num[ the];8 intN,count=0;9 DoubleAverage=0;TenCin>>N; One for(intI=0; i<n;i++){ A BOOLIsnumber=true;//Judging whether it is a legal number - intPoint=0;//Monitor the number of decimal points - intpoint_=0;//Monitor the number of digits after the decimal point theNum[i] = (Char*)malloc(Ten*sizeof(Char));//Application Space -Cin>>Num[i]; - intlen=strlen (Num[i]); - DoubleTemp=atof (Num[i]);//Convert a string to a number, use your own Baidu + if(temp<- +|| Temp> +) isnumber=false; - for(intj=0; j<len;j++) {//determine the individual characters of each element + if(point==1) point_++; A if(num[i][j]=='-'&&j!=0){//if it contains-, then-only one and in the first position atIsnumber=false; - Break; - } - if(num[i][j]!='.'){ - if((num[i][j]<'0'|| Num[i][j]>'9') && (num[i][j]!='-')){ -Isnumber=false; in Break; - } to}Else{//if it's a decimal point +point++; - } the if(point_>2|| Point>1){//If the decimal point is greater than one or the number of decimals is extra 2 *Isnumber=false; $ Break;Panax Notoginseng } - } the if(!isnumber) +cout<<"ERROR:"<<num[i]<<"is not a legal number"<<Endl; A Else { thecount++; +average+=temp; - } $ } $ if(count==1) -printf"The average of 1 number is%.2LF", average); - Else if(count==0) theprintf"The average of 0 numbers is Undefined"); - ElseWuyiprintf"The average of%d numbers is%.2LF", count,average/count); the return 0; -}
1054. Averaging (20)