为什么"operand = (operand*10) + (expression[i] - '0');"

Why "operand = (operand*10) + (expression[i] - '0');"

本文关键字:operand 为什么 expression      更新时间:2023-10-16

为什么下面的代码会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);
}

因为它被告知。假设你有 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。

相关文章: