PAT甲级目录 |
PAT乙级目录题目描述
B1054 求平均值
解题思路
方法一:可利用字符串读取、打印函数,分别对字符串进行处理,若字符串是合法的,则两者的结果应当一致。如合法,再判断数的范围,即可获得结果。
方法二:根据字符串的形式判断是否合法,合法特点:
- 字符串中只能出现数字或者小数点,不能有其他字符
- 最多只包含一个小数点
- 若有小数点,小数点的位置距字符串末尾最多两个字符,最少一个字符
- 转换后的数绝对值范围不能超过 1000.
易错点
也许陌生的知识点
sscanf(a, "%lf", &temp);
- 按照指定格式从字符串 a 中读取一个浮点数
- 所需头文件:cstdio
sprintf(b, "%.2lf",temp);
- 按照指定格式将浮点数转换为字符串输出到 b 中
- 所需头文件:cstdio
代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
知识兔td> | #include <cstring> #include <iostream> using namespace std; int () { int n, cnt = 0; char a[50], b[50]; double temp, sum = 0.0; cin >> n; for(int i = 0; i < n; i++) { scanf("%s", a); sscanf(a, "%lf", &temp); sprintf(b, "%.2lf",temp); int flag = 0; for(int j = 0; j < strlen(a); j++) { if(a[j] != b[j]) flag = 1; } if(flag || temp < -1000 || temp > 1000) { printf("ERROR: %s is not a legal numbern", a); continue; } else { sum += temp; cnt++; } } if(cnt == 1) { printf("The average of 1 number is %.2lf", sum); } else if(cnt > 1) { printf("The average of %d numbers is %.2lf", cnt, sum / cnt); } else { printf("The average of 0 numbers is Undefined"); } return 0; }
知识兔td> |
原文:大专栏 PAT B1054 求平均值(C++)