2014-12-11 48 views
2

我正在制作一个反向波兰记法计算器的程序,我想知道是否有人可以给我一些提示。计算器将从用户那里吸取一行,如2 3 + 7 4 - *;中间有空格,我想在每次操作后打印一个结果。我需要我的反向波兰记法计算器上的帮助

这里是我的代码

#include <iostream> 
#include <string> 
#include <stack> 
#include <sstream> 
using namespace std; 

int main() { 
    stack<float>stack; 
    int i; 
    float num,result,first,second; 
    char op,ch; 
    string str; 

    getline(cin,str); 
    istringstream is(str); 
    for(int i=0;i<str.size();i++) { 
    is>>num; 
    stack.push(num); 
    } 
    for (i=0;i<str.size();++i) { 
    ch=str[i]; 
    } 
    if (ch=='+'||'-'||'*'||'/') { 
    if (ch='+') { 
     first=stack.top(); 
     stack.pop(); 
     second=stack.top(); 
     stack.pop(); 
     result=first+second; 
     stack.push(result); 
     cout<<result; 
    } 
// } // missing from question 
//} 

我已经越来越奇异数作为结果的一部分。 我正确读取我的堆栈吗?

+0

为什么你在不可读的方式编写代码? – Shoe 2014-12-11 06:06:08

回答

0

干净而优雅的做法是将所有条目作为浮点数推入堆栈(如果不是它们是运算符),并在遇到操作符获取操作符时在堆栈上执行弹出操作。如果它的一名操作员执行两次弹出操作并执行操作并执行相应的操作并将结果推回堆栈

有线数字输出的原因是您在堆栈中也有运算符的浮点值,并且你循环查找运算符。因此,对于示例2 3 + 7 4 - *。您将堆栈设置为2 3 float(+)7 4 float( - )float(*)< - 作为堆栈顶部。所以当你循环查找字符串并找到'+'符号时。您添加float(*)和float( - )的值并将其推入堆栈。我希望这会使你的疑问清楚。 :)

编辑: 这是上述说明的代码。

#include <iostream> 
#include <string.h> 
#include <stack> 
#include <sstream> 
#include <stdlib.h> 

using namespace std ; 

int main() 
{stack<float>stack; 
int i; 
float num,result,first,second; 
char op,ch; 
string str,str1; 

getline(cin,str); 
istringstream is(str); 

for(;is>>str1;){ 

if(str1.compare("+")==0){ 

    first=stack.top(); 
    stack.pop(); 
    second=stack.top(); 
    stack.pop(); 


    stack.push(first+second); 

    }else if(str1.compare("-")==0){ 

    first=stack.top(); 
    stack.pop(); 
    second=stack.top(); 
    stack.pop(); 
    stack.push(first-second); 
    }else if(str1.compare("*")==0){ 

    first=stack.top(); 
    stack.pop(); 
    second=stack.top(); 
    stack.pop(); 
    stack.push(first*second); 
    }else if(str1.compare("/")==0){ 

    first=stack.top(); 
    stack.pop(); 
    second=stack.top(); 
    stack.pop(); 
    stack.push(first/second); 
    }else{ 

    stack.push(strtof(str1.c_str(),NULL));    
    } 
} 
cout<<"The result of the expression is:"<<stack.top(); 
} 
3

这可能不是你的唯一的问题,但你必须:

if (ch=='+'||'-'||'*'||'/') { 

时,你可能实际上意味着:

if (ch=='+' || 
    ch=='-' || 
    ch=='*' || 
    ch=='/') { 

而且有权根据您有:

if (ch='+') { 

你可能会采取行动ually意味着:

if (ch=='+') { 

=是分配(要设置ch'+'),而==是比较(要测试是否ch等于'+'