题意:根据条件判定哪些数是合法的,哪些是不合法的。求其中合法的数的平均值。
思路:字符串处理函数,考虑到最后输出的时候需要控制格式,因此选用scanf()和printf()。另外需要了解atof()函数,用的较多的是atoi(),但这里是浮点数的转换,所以不要搞错了。(两者都在头文件<stdlib.h>下)
代码:
#include <cstdio> #include <cstring> #include <cstdlib>//atof() #include <cctype>//isalpha(ch) bool judge(char str[]) { int len=strlen(str); int pointCnt=0,pointPos=-1; for(int i=0;i<len;i++){ if(str[i]=='.') { pointCnt++; pointPos=i; } if(isalpha(str[i])) return false;//如果含有字母 } if(pointCnt>1) return false;//如果含有多个小数点 if(pointPos!=-1 && len-1-pointPos>2) return false;//如果有一个小数点,但小数位数超过2位 double tmp=atof(str);//到这一步,str已经是个合法的数了,还需判断是否在给定范围内 if(tmp<-1000 || tmp>1000) return false; return true; } int main() { //freopen("pat.txt","r",stdin); int n,validCnt=0; char str[100]; double d,sum=0; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%s",str); bool isLegal=judge(str); if(isLegal){ validCnt++; sum+=atof(str); }else printf("ERROR: %s is not a legal number\n",str); }//for if(validCnt==0) printf("The average of 0 numbers is Undefined\n"); else if(validCnt==1) printf("The average of 1 number is %.2f\n",sum); else printf("The average of %d numbers is %.2f\n",validCnt,sum/validCnt); return 0; }