这道题很好,可以作为一个简便方法,即判断基本数据类型的某数是否合法,值得回顾。
#include<iostream> #include<cstring> using namespace std; char str1[5000],str2[5000]; int main() { int n,cnt = 0; double a,sum = 0; cin>>n; while(n--) { scanf("%s",str1); sscanf(str1,"%lf",&a); sprintf(str2,"%.2f",a); bool flag = true; for(int i = 0; i < strlen(str1); ++i) { //假设str1为2.333,str2为2.33,那么 str1与str2两值不相等 //假设str1为2.3, str2为2.30,那么 str1与str2两值相等 if(str1[i] != str2[i]) flag = false; } if(flag == false || a < -1000 || a > 1000) printf("ERROR: %s is not a legal number\n",str1); else { sum += a; cnt++; } } if(cnt == 0) printf("The average of 0 numbers is Undefined"); else if(cnt == 1) printf("The average of 1 number is %.2f",sum); else printf("The average of %d numbers is %.2f",cnt,sum/cnt); return 0; }
原文:https://www.cnblogs.com/keep23456/p/12345668.html