|
50鱼币
本帖最后由 claws0n 于 2018-10-22 18:37 编辑
大佬们好,我最近在学习数据结构,栈的过程中遇到了一个灵异事件。
我用C++写了一个后缀表达式计算器,但计算时,发现加、减、除都没有问题,但用到乘法时发现这玩意算出来是正确答案,但压入栈中的却是错误答案,而且错得好像……
算了,演示一下吧。
输入:25 5 *
输出:5.00
输入:25 2 *
输出:12.50
输入:81 9 *
输出:9.00
代码如下
- #include <iostream>
- #include <cstdio>
- #include <stack>
- using namespace std;
- typedef string::iterator strit;
- double calc(double x, double y, char op)
- {
- double result;
- switch (op)
- {
- case '+':
- result = x + y;
- break;
- case '-':
- result = x - y;
- break;
- case '*':
- result = x * y;
- case '/':
- result = x / y;
- }
- return result;
- }
- int main()
- {
- int t;
- string str;
- stack<double> st;
- double a, b, c;
-
- getline(cin, str);
-
- for (strit i = str.begin(); i != str.end(); ++i)
- {
- if (*i >= '0' && *i <= '9')
- {
- t = 0;
- for (; *i >= '0' && *i <= '9'; ++i)
- {
- t = t * 10 + *i - '0';
- }
- i--;
- st.push((double)t);
- }
- else if(*i == '+' || *i == '-' || *i == '*' || *i == '/')
- {
- b = st.top();
- st.pop();
- a = st.top();
- st.pop();
- c = calc(a, b, *i);
- st.push(c);
- }
- }
- printf("%.2f\n", st.top());
- return 0;
- }
复制代码
望大佬指点,代码写的不好的话也请指出,谢谢 |
|