为什么需要从 double 到 float 而不是从 int 到 byte 的显式类型转换? [英] why explicit type casting required from double to float but not from int to byte?

查看:26
本文介绍了为什么需要从 double 到 float 而不是从 int 到 byte 的显式类型转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下声明:

byte by = 5;//工作正常

文字 '5' 是 int 类型并且足够小以适应字节类型的变量.编译器在此处进行隐式类型转换(从 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 of type 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?

推荐答案

在整数版本中,编译器知道所有数字5中的数据都可以存储在 byte 中.不会丢失任何信息.对于浮点值,情况并非总是如此.例如,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 floatdouble 中完全表示,因此您可以争辩说,在这种情况下,不会丢失任何信息 - 但是语言规范必须使其有效:

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 的范围内(尽管即使 that 不是和你想象的一样简单)但是当谈到一个文字是否可以被精确表示时,我认为它永远没有详细说明.

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 的显式类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆