后缀表达式求值 C++ 程序有问题,执行a.out '2 1 -'结果是 -1,需要怎么修改?

来源:百度知道 编辑:UC知道 时间:2024/09/23 06:38:32
#include <iostream>
#include <cstring>
#include "STACK.cxx"
using namespace std;

int main(int argc, char *argv[])
{
char *a=argv[1];
int N = strlen(a);
STACK<signed int> save(N);
for (int i=0; i<N; i++)
{
if (a[i]== '+')
save.push(save.pop()+save.pop());
if (a[i]== '*')
save.push(save.pop()*save.pop());
if (a[i]== '-')
{
save.push(save.pop()-save.pop()); //就算这里掉换顺序也一样
}
if (a[i]=='/')
save.push(save.pop()/save.pop());
if((a[i]>='0')&&(a[i]<='9'))
save.push(0);
while ((a[i]>='0')&&(a[i]<='9'))
save.push(10*save.pop()+(a[i++]-'0'));
}
cout << save.pop() << endl;
}

你不能这样用啊save.push(save.pop()-save.pop()); //就算这里掉换顺序也一样

可以这样啊:
int a = save.pop();
int b = save.pop();

if (a[i]== '-')
{
save.push(b-a); //ok吧
}

恩,1楼的 用了简化蛮好 的,LZ可以试下1楼的