2006年浙江大学计算机及软件工程研究生机试真题-简单计算器

来源:互联网 发布:乔杉咖啡厅网络剧 编辑:程序博客网 时间:2024/06/05 00:51
题目描述:
    读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
输入:
    测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
输出:
    对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
样例输入:
1 + 24 + 2 * 5 - 7 / 110
样例输出:
3.00

13.36


代码:

#include<iostream>#include<string>#include<cstdio>#include<stack>using namespace std;int OptoInt(char c){switch (c){case '+':return 1;case '-':return 2;case '*':return 3;case '/':return 4;}}int main(){string s;while (getline(cin, s)){if (s == "0")break;stack<int> op;stack<double> num;for (int i = 0; i < s.size(); i++){if (s[i] == ' ')continue;if (isalnum(s[i])){double x = 0;while (s[i++] != ' ' && i<s.size() + 1){x = 10 * x + (s[i - 1] - '0');}i--;num.push(x);continue;}if (s[i] != ' '){int n1 = OptoInt(s[i]);if (op.empty() || n1>op.top()){op.push(n1);}else{double tmp;while (!op.empty() && n1 <= op.top()){int ret = op.top();op.pop();double b = num.top();num.pop();double a = num.top();num.pop();switch (ret){case 1:tmp = a + b; break;case 2:tmp = a - b; break;case 3:tmp = a * b; break;case 4:tmp = a / b; break;}num.push(tmp);}op.push(n1);}}}while (!op.empty()){double tmp;int ret = op.top();op.pop();double b = num.top();num.pop();double a = num.top();num.pop();switch (ret){case 1:tmp = a + b; break;case 2:tmp = a - b; break;case 3:tmp = a * b; break;case 4:tmp = a / b; break;}num.push(tmp);}printf("%.2lf\n", num.top());}return 0;}


0 0
原创粉丝点击