程序应读取由数字和运算符组成的后缀表达式并计算结果。我尝试使用string
,但我不断得到一个结果。你能告诉我我做错了什么吗?
#include <iostream>
#include "StackADT.h"
#include <stack>
using namespace std;
#include <string>;
bool isOperator(string);
int calculate (int, char, int);
void display (int, string, int, int);
int main(){
string expr;
int operand2 = 0;
int operand1 = 0;
string thisOperator;
int value;
int result;
cout << "Evaluates a postfix expression(to Quit)." << endl;
cin >> expr;
//while(expr != "-1")
{
//getline( cin, expr,'\n' );
int exprSize = expr.size();
const int siz = 10;
char expr2[siz];
for (int i = 0; i < expr.length; i++)
{
expr2[i] = expr[i];
}
Stack<int> stack;
int index = 0;
while (index < exprSize){
if (!isOperator(expr[index]) )
{
stack.pushStack(expr[index]);
}
else
{
stack.popStack (operand2);
stack.popStack (operand1);
thisOperator = expr[index];
value = calculate (operand1, thisOperator[index], operand2);
stack.pushStack(value);
}
index++;
}
result = stack.popStack (operand1);
display(operand1, thisOperator, operand2, result );
// cout << "Evaluates a postfix expression(to Quit)." << endl;
// cin >> expr;
}
system("pause");
return 0;
}
void display (int op1, string operat, int op2, int result){
cout << op1 << operat << op2 << " = " << result;
}
bool isOperator(char token )
{
if(token == '-' || token == '+' || token == '*' || token == '/')
return true;
else
return false;
}
int calculate (int op1, char operat, int op2){
switch (operat)
{
case '/': return op1 / op2;
break;
case '+': return op1 + op2;
break;
case '*': return op1 * op2;
break;
case '-': return op1 - op2;
break;
default: cout << "Cant / by zero" << endl;
break;
}
}
我正在解决这个问题;exprSize = 字符串长度
- 创建堆栈(堆栈)
- 索引 = 0
- 循环(索引 < exprSize)
- if (expr[index] 是操作数)
- pushStack (stack, expr[index])
- else // expr[index] 是一个运算符
- popStack(堆栈,操作数2)
- popStack(堆栈,操作数1)
- 运算符 = expr[索引]
- 值 = 计算(操作数 1、运算符、操作数 2)
- pushStack(堆栈,值)
- 万一
- 索引 = 索引 + 1
- if (expr[index] 是操作数)
- 结束循环
- popStack(堆栈,结果)
- 返回(结果)