将int分配给byte vs double以浮点数在Java中 [英] assign int to byte vs double to float in java

查看:49
本文介绍了将int分配给byte vs double以浮点数在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1.当我们将 double分配给float变量时,编译器将给我们错误

1.when we assign double to float variable compiler gives us error

float f = 2753.2211;

可能会丢失精度.

2.当我们将 int分配给字节变量时,编译器不会给我们错误

possible loss of precision Required to cast.

2.when we assign int to byte variable compiler don't gives us error

byte b = 24;

确定

OK

在第二种情况下,数据也可能丢失.那么为什么显式强制转换是不必要的呢?

In second case data can also be lost.Then why casting explicitly is not necessary.?

推荐答案

JLS明确允许第二种情况作为特殊情况.在 JLS 5.2 中,该文档用于缩小转换范围,它说:

The second case is explicitly allowed by the JLS as a special case. In JLS 5.2, which deals with narrowing conversions, it says:

此外,如果表达式是常量表达式(§15.28)类型为byte,short,char或int:

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

  • 如果变量的类型为byte,short或char,并且常量表达式的值可以表示为变量的类型,则可以使用缩窄基元转换.

...

换句话说,对于非 long 类整数值,您可以隐式地缩小它们 iff 您要缩小的值是一个适合您指定的类型.

In other words, for the non-long integer-like values, you can implicitly narrow them iff the value you're narrowing is a constant that fits within the type you're specifying.

我猜测对浮点数不会应用相同的技巧,因为浮点值比整数值更难处理.例如,不能精确地以浮点表示0.1,而可以精确地表示1.0.这意味着 double d = 0.1 并不是实际上将值0.1放入 d 中-只是非常接近0.1的值.鉴于此,完全适合"规则甚至不适用于浮点字面量,当我们缩小时是否完全适合"的问题变得更加棘手.您的选择基本上是:

I'm guessing the same trick isn't applied to floats because floating point values are trickier than integer values. For instance, 0.1 can't be exactly expressed in a floating point, while 1.0 can. That means that double d = 0.1 isn't actually putting the value 0.1 into d -- just a value that's very close to 0.1. Given that, the "does it fit exactly" rule doesn't apply even to floating point literals, and the question of "does it fit exactly when we narrow" becomes trickier. Your options would basically be:

  • 始终允许它(如果值与其文字表示形式明显不同,则可能会导致某些令人惊讶的行为)
  • 仅在可以精确输入值 的情况下才允许使用它.这看起来非常不一致:
    • float f1 = 1.0 double d1 = 1.0 都可以工作
    • double d2 = 0.1 可以工作,但是 float f2 = 0.1 不能-令人困惑!
    • always allow it (which could cause some surprising behavior if a value is significantly different than its literal representation)
    • only allow it if the value can be exactly put in. This would look highly inconsistent:
      • float f1 = 1.0 and double d1 = 1.0 both work
      • double d2 = 0.1 works, but float f2 = 0.1 doesn't -- confusing!

      考虑到这些选项,JLS的设计者似乎选择了三个不大的选项中的最少一个.

      Given these options, it seems that the designers of the JLS chose the least of three not-great options.

      这篇关于将int分配给byte vs double以浮点数在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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