PAT甲级A1108 Finding Average (20分)/字符串

深藏阁楼爱情的钟 2023-06-29 05:59 105阅读 0赞

题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805360777347072

读几个数,不合法就报错,计算合法的数量和平均数。

构思这种题,一开始就要思考测试点都在哪,这样才能有的放矢嘛——最保险的思路就是题目有说的,都当测试点,没说的地方,对于这种20分的题,先不要管。

这道题的测试都是浅显的覆盖了以下情况:
1、(易错点)有没有分合法的数的数量是0、1、其他,其中0和其他的number带s,1的不带s;
2、带两个小数点以上的数
3、含有除了数字、符号、小数点以外的数,如aaa
4、小数位数超过两位的数
5、大小不在[-1000,1000]范围内的数
6、(易错点)输出的小数要是两位的

不需要考虑的点:
1、输入的数是1.000、2.000等,后面带0的小数超过了2位,合法不合法
2、输入带两个负号的,合法不合法

满分代码如下:

  1. int main(){
  2. int n,num=0;
  3. double total=0.0;
  4. cin>>n;
  5. string s;
  6. for(int i=0;i<n;i++){
  7. cin>>s;
  8. bool f=true;
  9. int dot=0;
  10. int len=s.size();
  11. for(int j=0;j<len;j++){
  12. if(s[j]=='-'&&j>0){
  13. f=false;
  14. }
  15. if(s[j]!='-'&& s[j]!='.' && !isdigit(s[j])){
  16. f=false;
  17. }
  18. if(s[j]=='.'){
  19. dot++;
  20. }
  21. }
  22. if(f && dot>1){
  23. f=false;
  24. }
  25. if(f){
  26. int pos=s.find('.');
  27. if(pos!=-1){
  28. int zero=s.find_last_not_of('0');
  29. //int zero=s.size()-1;
  30. if(zero-pos>2){
  31. f=false;
  32. }
  33. }
  34. }
  35. if(f && (stof(s)>1000.0 || stof(s)<-1000.0)){
  36. f=false;
  37. }
  38. if(!f){
  39. cout<<"ERROR: "<<s<<" is not a legal number"<<endl;
  40. }else{
  41. num++;
  42. total+=stod(s);
  43. }
  44. }
  45. if(num==0){
  46. cout<<"The average of 0 numbers is Undefined";
  47. }else if(num==1){
  48. printf("The average of 1 number is %.02lf",total);
  49. }else{
  50. printf("The average of %d numbers is %.02lf",num,(double)total/num);
  51. }
  52. return 0;
  53. }

发表评论

表情:
评论列表 (有 0 条评论,105人围观)

还没有评论,来说两句吧...

相关阅读