为什么在Java中可以让整数和浮点数一起进行操作?

huangapple go评论75阅读模式
英文:

Why is it possible for an int and a float to operate together in Java?

问题

public static void main(String[] args) {
    float result = (int)Math.floor(1.5F);
    System.out.println(result);

所以这是我放入Java的内容
但我想知道的是...
应该是
float result = (float)Math.floor(1.5F);

因为结果是在寻找一个float但是(int)Math.floor(1.5F)会产生一个int
或者至少是我这个新手大脑所思考的 :/
英文:
public static void main(String[] args) {
     float result = (int)Math.floor(1.5F);
        System.out.println(result);

so this is what I plugged into java
but what I'm wondering is...
shouldn't it be:
float result = (float)Math.floor(1.5F); ?

because the result is looking for a float but (int)Math.floor(1.5F) produces an int
or atleast thats what my noob brain is thinking :/

答案1

得分: 3

这是Java中的宽化原始类型转换的示例。有关更多信息,请参阅官方Java规范(滚动到5.1.2. 宽化原始类型转换和相关的5.1.3. 收窄原始类型转换部分)。

具体在你的情况下,你正在看到:

将int或long值进行宽化转换为float,或将long值进行宽化转换为double,可能会导致精度丢失 - 也就是说,结果可能会丢失一些值的最不显著位。在这种情况下,得到的浮点值将是整数值的正确舍入版本,使用IEEE 754最近舍入模式(§4.2.4)。

英文:

This is an example of Widening Primitive Conversion in Java. See the official Java spec for more information (scroll down to 5.1.2. Widening Primitive Conversion and the related 5.1.3. Narrowing Primitive Conversion).

Specifically in your case, you're seeing:

> A widening conversion of an int or a long value to float, or of a long
> value to double, may result in loss of precision - that is, the result
> may lose some of the least significant bits of the value. In this
> case, the resulting floating-point value will be a correctly rounded
> version of the integer value, using IEEE 754 round-to-nearest mode
> (§4.2.4).

huangapple
  • 本文由 发表于 2020年8月11日 10:41:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63350727.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定