为什么以下代码正在执行operand * 10
?为什么它不是operand = (expression[i] - '0');
而不是operand = (operand*10) + (expression[i] - '0');
else if(IsNumericDigit(expression[i]))
{
int operand = 0;
while(i<expression.length() && IsNumericDigit(expression[i]))
{
operand = (operand*10) + (expression[i] - '0');
// why is he doing operand *10?
// example : if have a string 2 3 * 3 4 +.
// It is pushing 23 on stack rather than 2 and 3
i++;
}
i--;
S.push(operand);
}
答案 0 :(得分:0)
因为被告知了。考虑你有2 3 4 5 i你的表达式数组。然后您的代码operand = (operand*10) + (expression[i] - '0');
将执行以下操作:
operand = (0*10) + (2-0)
operand = (2*10) + (3-0)
operand = (23*10) + (4-0)
operand = (234*10) + (5-0)
所以最后你的操作数将包含2345号。就像你在纸上写下数字一样。首先你写下2,然后你写下3。现在你有23与20 + 3相同。因此乘以10。