why explicit type casting required from double to float but not from int to byte?

前端 未结 4 1379
失恋的感觉
失恋的感觉 2020-12-20 20:32

Consider following statement:

byte by = 5; //works fine

literal \'5\' is of type int and small enough to fit into a variable of type byt

4条回答
  •  执笔经年
    2020-12-20 21:12

    In the integer version, the compiler knows that all the data in the number 5 can be stored in a byte. No information is lost. That's not always true for floating point values. For example, 0.1f isn't equal to 0.1d.

    Now for the example, you've given, the decimal value 5.5 is exactly represented in both float and double, so you could argue that in that case, no information is lost - but it would be pretty odd for the language specification to have to make this valid:

    float f = 5.5;
    

    but this invalid:

    float f = 5.6;
    

    The language specification is happy to talk about whether a number fits within the range of float/double (although even that isn't as simple as you might expect) but when it comes to whether a literal can be exactly represented, I don't think it ever goes into detail.

提交回复
热议问题