gpt4 book ai didi

c++ - 评估后缀

转载 作者:行者123 更新时间:2023-11-28 08:21:39 25 4
gpt4 key购买 nike

我的代码假设计算后缀表达式的值。但我被困在“结果”上,我不知道如何编写代码。我写道:result = operand1 operation.push operand2 逻辑上会报错。我使用了 2 个堆栈。

int main() 
{
string input;
cout << "Enter a postfix expression: " << endl;
getline(cin, input);

double operand1, operand2, result;
stack<double> number;
stack<char>operation;

int i=0;
while (i < input.length())
{
if (input[i] == '+' || input[i] == '-' || input[i] == '*' || input[i] == '/' || input[i] == '^')
operation.push(input[i]);
else
number.push(input[i]);
i++;
}

operand2 = number.top( );
number.pop( );
operand1 = number.top( );
number.pop( );
result = operand1 operation.push(input[i]) operand2
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return 0;
}

谁能提出更好的解决方案?谢谢

最佳答案

您需要对运算符进行切换并自行计算结果:

char op = operation.top();
switch( op ) {
case '+': result = operand1 + operand2; break;
case '-': result = operand1 - operand2; break;
case '*': result = operand1 * operand2; break;
case '/': result = operand1 / operand2; break;
case '^': result = pow(operand1, operand2) ; break;
}

关于c++ - 评估后缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5622099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com