1054. 求平均值 (20)
来源:互联网 发布:用matlab求矩阵方程 编辑:程序博客网 时间:2024/06/04 23:33
本题的基本要求非常简单:给定N个实数,计算它们的平均值。但复杂的是有些输入数据可能是非法的。一个“合法”的输入是[-1000,1000]区间内的实数,并且最多精确到小数点后2位。当你计算平均值的时候,不能把那些非法的数据算在内。
输入格式:
输入第一行给出正整数N(<=100)。随后一行给出N个实数,数字间以一个空格分隔。
输出格式:
对每个非法输入,在一行中输出“ERROR: X is not a legal number”,其中X是输入。最后在一行中输出结果:“The average of K numbers is Y”,其中K是合法输入的个数,Y是它们的平均值,精确到小数点后2位。如果平均值无法计算,则用“Undefined”替换Y。如果K为1,则输出“The average of 1 number is Y”。
输入样例1:
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35
输出样例1:
ERROR: aaa is not a legal number
ERROR: 9999 is not a legal number
ERROR: 2.3.4 is not a legal number
ERROR: 7.123 is not a legal number
The average of 3 numbers is 1.38
输入样例2:
2
aaa -9999
输出样例2:
ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefined
解题思路
其实本题不难,做好判断就好了,但是要注意一个测试点,我已经在题目中把字体加粗了,这两句英文的Number是不一样的一个是Number另一个是Numbers,博主就是粗心被这个测试点给弄了。
#include<iostream>#include<string>#include<iomanip>#include<math.h>using namespace std;int main() { int T,cnt1=0,cnt2=0,cnt3=0;//cnt3小数点后多少位 string *arr; string s_num; double d_num; double sum = 0; bool flag,lit;//lit:小数点是否出现 double ret; cin >> T; arr = new string[T]; for (int i = 0; i < T;i++) { cin >> s_num; flag = true; lit = false; cnt3 = 0; for (string::iterator i = s_num.begin(); i != s_num.end(); ++i) {//检测每个位置的值是否为数字 if (*i == '-') { if (i != s_num.begin()) { flag = false; break; } else continue; } if (lit) { cnt3++; if (cnt3 > 2) { flag = false; break; } } if (*i == '.') { if (!lit) { lit = true; continue; } else { flag = false; break; } } if (!(*i >= '0' && *i <= '9')) { flag = false; break; } } if (flag) { d_num = stod(s_num); if (d_num <= 1000 && d_num >= -1000) { cnt1++; sum += d_num; } else { arr[cnt2++] = s_num; } }else{ arr[cnt2++] = s_num; } } for (int i = 0; i < cnt2;++i) { cout << "ERROR: " << arr[i] << " is not a legal number"<<endl; } ret = sum / cnt1; if (cnt1 != 0) { if (cnt1 == 1) cout << fixed << setprecision(2) << "The average of " << cnt1 << " number is " << ret << endl; else cout << fixed << setprecision(2) << "The average of " << cnt1 << " numbers is " << ret << endl; }else cout << "The average of 0 numbers is Undefined" << endl; return 0;}
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- 1054. 求平均值 (20)
- Java多线程之内存可见性
- 剑指offer——面试中的各项能力
- 安卓——套接字Socket通信(未完)
- CentOS6.7安装独立版Spark
- java 设计模式之工厂方法模式
- 1054. 求平均值 (20)
- mystring类的实现
- CEF:MFC 对话框 Demo(VS2013)
- 关于CSS 伪类及伪元素
- 【Docker安装】- Ubuntu14.04中安装最新版的Docker
- 斐波拉契数列
- 错误Error:Could not get unknown property 'GROUP' for object of type org.gradle.api.publication.maven.i
- HDOJ 2602 Bone Collector(0-1背包)
- git