1108. Finding Average 解析
来源:互联网 发布:知乎怎么回答问题 编辑:程序博客网 时间:2024/06/07 12:38
用string读入,然后进行判定,有字母的非法,有几个小数点的非法,小数点超过2位的非法。
特别要注意读入的数要在[-1000,1000]之间。
最后还要注意,number和numbers。
#include <iostream>#include <string>#define MAX 110using namespace std;int n;string list[MAX];int sum;bool Check(string s) {int p = 0;int dec = 0;bool isdec = false;bool isneg = false;while (p < s.size()) {if ((s[p] < '0' || s[p] > '9') && s[p] != '.' && s[p] != '-')return false;else if (s[p] == '.') {if (isdec) return false;isdec = true;}else if (s[p] == '-') {if (isneg) return false;isneg = true;}else {if (isdec)dec++;if (dec > 2)return false;}p++;}return true;}float str2fl(string s) {float n = 0;bool isNeg = false;bool isDec = false;int decPos = 1;for (int i = 0; i < s.size(); i++) {if (s[i] == '-') {isNeg = true;continue;}else if (s[i] == '.') {isDec = true;continue;}else {if (!isDec) {n *= 10;n += (s[i] - '0');}else {if (decPos == 1) {n += 0.1 * (s[i] - '0');decPos++;}else if (decPos == 2) {n+=0.01 * (s[i] - '0');decPos++;}}}}if (n > 1000 || n < -1000) {cout << "ERROR: " << s << " is not a legal number" << endl;return -1;}if (isNeg)return -n;return n;}int main() {cin >> n;string temp;float sum = 0, num = 0;float tempf;for (int i = 0; i < n; i++) {cin >> temp;if (!Check(temp))cout << "ERROR: " << temp << " is not a legal number" << endl;else {tempf = str2fl(temp);if (tempf != -1) {sum += tempf;num++;}}}if (num != 0 && num != 1)printf("The average of %.0f numbers is %.02f\n", num, sum/num);else if(num == 1)printf("The average of %.0f number is %.02f\n", num, sum / num);elsecout << "The average of 0 numbers is Undefined" << endl;return 0;}
0 0
- 1108. Finding Average 解析
- 1108. Finding Average (20)
- 1108. Finding Average
- 1108. Finding Average (20)
- 1108. Finding Average (20)
- 1108. Finding Average
- PAT--1108. Finding Average
- 1108. Finding Average (20)
- 1108. Finding Average (20)
- 1108. Finding Average (20)
- 1108. Finding Average
- 【PAT】1108. Finding Average
- 1108. Finding Average (20)
- 1108. Finding Average (20)
- 1108. Finding Average (20)
- pat 1108. Finding Average
- 1108. Finding Average (20)
- 1108. Finding Average (20)
- LeetCode刷题(C++)——Balanced Binary Tree(Easy)
- Java笔记之浅析String以及Stringbuffer
- Java笔记之JVM内存区浅析
- TaoSama Becomes the God of Stocks dp
- 【最短路】POJ2502 SUBWAY (spfa)
- 1108. Finding Average 解析
- web.py自定义not found 实例
- 浅谈Java反射的实现原理
- Android: unable to start service intent: u0 not found
- Spark选择Scala的理由
- 洛谷 P1019 单词接龙
- Spring mvc,jQuery和JSON数据交互
- JAVA经典算法-冒泡排序和快速排序
- 欧几里得算法(辗转相除)