我正在尝试编写一个计算器来计算输入的后缀表达式。
目前我正在尝试使用字符数组获取输入,但效果不佳。也许你有一个更好的输入结构的建议。或许你不能发现任何其他错误,因为我得到了错误的结果......
正如你可以看出我对C ++还不熟悉。
到目前为止我的代码:
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <stack>
#include <string.h>
using namespace std;
int performOperation(int operand1, int operand2, char op)
{
int ans;
switch (op) {
case '+':
ans = operand2 + operand1;
break;
case '-':
ans = operand2 - operand1;
break;
case '*':
ans = operand2 * operand1;
break;
case '/':
ans = operand2 / operand1;
break;
}
return ans;
}
bool checkOperator(char character)
{
if (character == '+' || character == '-' || character == '*' || character == '/')
return true;
else
return false;
}
int solvePostfix(char postfix[], int size) {
stack<int> s;
int i = 0;
char character;
int value;
value = 0;
while (i < size)
{
character = postfix[i];
if (isdigit(character)) //ist Operand, pushe ihn auf Stack s
{
s.push(character);
}else if (checkOperator(postfix[i])) //ist Operator, nehme die zwei Operanden vom Stack und benutze den Operator
{
int operand1 = s.top();
s.pop();
int operand2 = s.top();
s.pop();
value = performOperation(operand1, operand2, character);
s.push(value); //pushe den Ergebniswert auf Stack
}
i++;
}
return value;
}
int main()
{
char exp[100];
cout << "Bitte Postfix eingeben: " << endl;
cin >> exp;
int size = sizeof(exp);
int val = solvePostfix(exp, size);
cout << "\nErgebnis ist: " << val << endl;
}