简体   繁体   English

Postfix表达式中的等于运算符

[英]Equal operator in Postfix expression

I'm evaluating postfix expression in c++. 我正在用C ++评估postfix表达式。 Everything is working fine but I've not managed the = equal operator properly. 一切工作正常,但我没有正确管理= equal运算符。

The Problem causing Infix Expression look like this: A = 2 + B = 5 where A and B are variables. 导致中缀表达式的问题看起来像这样: A = 2 + B = 5其中A和B是变量。 My program convert it into postfix as: 2 5 = B + = A . 我的程序将其转换为后缀为: 2 5 = B + = A

In my program I wrote that if current element is an equal operator followed by a variable then move the result in that variable. 在我的程序中,我写道, if current element is an equal operator followed by a variable then move the result in that variable. Which is not proper way to do because my program after solving the above expression gives B = 5 and A = 7 which seems wrong from the expression. 这不是正确的方法,因为我的程序在解决上述表达式后给出B = 5A = 7 ,这从表达式看来似乎是错误的。

Which technique should I follow to handle the equal operator for my code? 我应该遵循哪种技术来处理代码的相等运算符?

As the comments say, the answer you get is consistent with the rule If current element is an equal operator followed by a variable then move the result in that variable . 就像评论说的那样,您得到的答案与规则一致。 如果当前元素是一个相等的运算符,后跟一个变量,则将结果移动到该变量中

However, there is something in the rule that breaks the uniformity of the postfix notation, so I would rather recommend changing that rule to 但是,该规则中有某些东西会破坏后缀符号的统一性,因此我宁愿建议将该规则更改为

If the current element is an assignment operator then move the first operand (anything) to the second operand (variable) 如果当前元素是赋值运算符,则将第一个操作数(所有)移动到第二个操作数(变量)

For this rule to be applicable you have to validate that the last token (second operand) is a variable. 为了使此规则适用,您必须验证最后一个标记(第二个操作数)是否为变量。

The rule I propose is consistent with other operations. 我提出的规则与其他操作一致。 For instance the postfix notation 3 4 + is converted to 3 + 4 because by the time your scanner reads + it will take the last two operands, 3 and 4 , and sum them: 3 + 4 . 例如,后缀表示法3 4 +转换为3 + 4因为到扫描仪读取+ ,它将采用最后两个操作数34并将它们求和: 3 + 4 In the same way 3 4 + A = would proceed by first saving 3 + 4 as the first operand, then A as the second and finally moving the first operand to the second A = 3 + 4 . 以同样的方式进行3 4 + A =的操作,首先将3 + 4保存为第一个操作数,然后A作为第二个操作数,最后将第一个操作数移动到第二个A = 3 + 4 Instead, the way you devised the assignment rule is special in that it first reads the operator = and then the second operand A , which will work, but not in the same way as the rest of the operations. 相反,您设计分配规则的方式很特殊,因为它首先读取运算符= ,然后读取第二个操作数A ,这将起作用,但与其余操作的方式不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM