简单计算器
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 24138 Accepted Submission(s): 8750
Problem Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 2 3 |
1 + 2 4 + 2 * 5 - 7 / 11 0 |
Sample Output
1 2 |
3.00 13.36 |
可以把整个式子视为若干个数相加(减)。遇到乘除项时与上一项合并即可。
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
#include <cstdio> #include <cstring> #include <cmath> #include <string> #include <iostream> #include <istream> #define forr(a,b,c) for(int a=b;a<=c;a++) #define MAX(a,b) (a>b)?a:b; #define MIN(a,b) (a<b)?a:b; #define memsett(a) memset(a,sizeof(a),0); using namespace std; string s; double a[300]; int main() { while (true) { memsett(a); getline(cin,s); if ((s.length()==1)&&(s[0]=='0'))return 0; int num = 0; int type = 1; int cache = 0; forr(i, 0, s.length()-1) { if (s[i] == ' ') { if (type == 1) { num++; a[num] = cache; cache = 0; } if (type == 2) { num++; a[num] = -cache; cache = 0; } if (type == 3) { a[num] = a[num]*cache; cache = 0; } if (type == 4) { a[num] = a[num]/cache; cache = 0; } continue; } if (s[i] == '+') { type = 1; i++; continue; } if (s[i] == '-') { type = 2; i++; continue; } if (s[i] == '*') { type = 3; i++; continue; } if (s[i] == '/') { type = 4; i++; continue; } if ((s[i] >= '0') && (s[i] <= '9'))cache = cache * 10 + (s[i] - '0'); } if (type == 1) { num++; a[num] = cache; } if (type == 2) { num++; a[num] = -cache; } if (type == 3) { a[num] = a[num] * cache; } if (type == 4) { a[num] = a[num] / cache; } double output=0; forr(i, 1, num) { output += a[i]; } printf("%.2lf\n", output); } } |