后缀表达式的计算器程序

时间:2013-10-13 16:35:44

标签: c++

程序应该读取由数字和运算符组成的后缀表达式并计算结果。我尝试使用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 =字符串的长度

  1. createStack(stack)
  2. index = 0
  3. loop(index&lt; exprSize)
    1. if(expr [index]是操作数)
      1. pushStack(stack,expr [index])
    2. else // expr [index]是一个运算符
      1. popStack(stack,operand2)
      2. popStack(stack,operand1)
      3. operator = expr [index]
      4. value = calculate(operand1,operator,operand2)
      5. pushStack(stack,value)
    3. 结束如果
    4. index = index + 1
  4. 结束循环
  5. popStack(stack,result)
  6. return(result)

0 个答案:

没有答案