-4

If I compile this code:

int celsius = 41; double result = celsius *9/5 + 32;

I get a result of 105.0, but casting celsius as double gets me the correct result of 105.8

int celsius = 41; double result = (double)celsius *9/5 + 32;

Why I need to cast?

1 Answers1

2

celsius *9/5 + 32 is an expression that contains only integral values; it is an integer expression. It is therefore computed using integer arithmetic.

Finally, when you assign the integer result to a double variable, the integer is converted to double.

In (double)celsius *9/5 + 32, first of all the celsius value is converted to double. Then we want to multiply a double by 9, so integer 9 is converted to the double 9.0. Then we want to divide a double by 5, so integer 5 is converted to the double 5.0. Finally we want to add to the double the value 32, which is therefore converted to 32.0.

(In fact the conversion of the constants can be done at compile time, but you should get the point; it's the type of the operands that matters)