Does one double promote every int in the equation to double?

后端 未结 4 1949
粉色の甜心
粉色の甜心 2020-12-06 09:13

Does the presence of one floating-point data type (e.g. double) ensure that all +, -, *, /, %, etc math operations assume double operands?

If the story

4条回答
  •  既然无缘
    2020-12-06 09:50

    You must consider the precedence of every operator, you must think like a parser:

    double result1 = a + b/d + c; // equal to 4 or to 4.5?
    

    That's like a + (b/d) +c because the '/' operator has the biggest precedence.Then it doesn't matter what of these 2 operations is made for first, because the floating point operand is in the middle, and it "infects" other operands and make them be double.So it's 4.5.

    double result2 = (a + b)/d + c; // equal to 3 or to 3.75?  
    

    Same here, it's like ((a+b)/d )+c, so a+b is 3, that 3 becomes a floating point number because gets promoted to double, because is the dividend of d, which is a double, so it's 0.75+3, that is 3.75.

    double result3 = a/b + d; // equal to 4 or to 4.5?
    

    It's like (a/b)+d, so a/b is zero and d is 4, so it's 4. A parser makes all the operations in order of precedence, so you can exactly know what will be the result of the expression.

提交回复
热议问题