gpt4 book ai didi

c++ - 后缀评估

转载 作者:太空宇宙 更新时间:2023-11-04 14:02:03 26 4
gpt4 key购买 nike

我正在编写一个代码来评估给定的后缀表达式。每个操作数和运算符由一个空格分隔,最后一个运算符后跟一个空格和一个“x”。

示例:

中缀表达式:(2*3+4)*(4*3+2)

后缀表达式:2 3 * 4 + 4 3 * 2 + * x

x”表示表达式结束。

输入(后缀表达式)由另一个将中缀表达式转换为后缀表达式的函数作为字符串给出。

后缀求值的函数是:

int pfeval(string input)
{
int answer, operand1, operand2, i=0;
char const* ch = input.c_str();
node *utility, *top;
utility = new node;
utility -> number = 0;
utility -> next = NULL;
top = new node;
top -> number = 0;
top -> next = utility;

while((ch[i] != ' ')&&(ch[i+1] != 'x'))
{
int operand = 0;
if(ch[i] == ' ') //to skip a blank space
i++;
if((ch[i] >= '0')&&(ch[i] <= '9')) //to gather all digits of a number
{
while(ch[i] != ' ')
{
operand = operand*10 + (ch[i]-48);
i++;
}
top = push(top, operand);
}
else
{
top = pop(top, operand1);
top = pop(top, operand2);
switch(ch[i])
{
case '+': answer = operand2 + operand1;
break;
case '-': answer = operand2 - operand1;
break;
case '*': answer = operand2 * operand1;
break;
case '/': answer = operand2 / operand1;
break;
case '^': answer = pow(operand2, operand1);
break;
}
top = push(top, answer);
}
i++;
}
pop(top, answer);
cout << "\nAnswer: " << answer << endl;
return 0;
}

我给出的示例的输出应该是“140”,但我得到的是“6”。请帮我找出错误。

push和pop方法如下(万一有人要复习):

class node
{
public:
int number;
node *next;
};

node* push(node *stack, int data)
{
node *utility;
utility = new node;
utility -> number = data;
utility -> next = stack;
return utility;
}

node* pop(node *stack, int &data)
{
node *temp;
if (stack != NULL)
{
temp = stack;
data = stack -> number;
stack = stack -> next;
delete temp;
}
else cout << "\nERROR: Empty stack.\n";
return stack;
}

最佳答案

while((ch[i] != ' ')&&(ch[i+1] != 'x'))

一旦 a) 当前字符是空格, b) 下一个字符是“x”,您就退出此循环。当前角色在此过程的早期就变成了一个空格;您只处理字符串的一小部分。

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

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