问题描述
考虑以下声明:
byte by = 5; //工作正常
字面数'5'的类型为int,小到足以容纳byte类型的变量。编译器在这里执行隐式类型转换(从int到byte)。
literal '5' is of type int and small enough to fit into a variable of type byte. Compiler does the implicit type casting here (from int to byte).
现在考虑以下场景:
float fl = 5.5; //compilation error
文字'5.5'的类型为double,也足够小以适应变量
类型的浮点数。为什么我们需要像这样显式地输入:
literal '5.5' is of type double, also small enough to fit into a variable oftype float. Why do we need to explicitly type cast like this:
float fl = (float) 5.5; //works fine
为什么编译器在浮点数的情况下不为我们进行转换?
Why compiler is not doing the casting for us in case of floating points?
推荐答案
在整数版本中,编译器知道 all 数字 5 可以存储在字节
中。没有信息丢失。浮点值并不总是如此。例如, 0.1f
不等于 0.1d
。
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
.
现在举例说明,你已经给出了小数值5.5 在 float
和 double ,所以你可以争辩说,在这种情况下,没有信息丢失 - 但语言规范必须使其有效是非常奇怪的:
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;
但是这个无效:
float f = 5.6;
语言规范很乐意谈论一个数字是否符合 float / double
(尽管 并不像你想象的那么简单)但是当它出现时是否可以准确表示文字,我认为永远不会详细说明。
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.
这篇关于为什么显式类型转换需要从double到float而不是从int到byte?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!