为什么在Java中进行类型转换会给我这些奇怪的结果?

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

Why casting give me these weird results Java?

问题

以下是您要求的代码部分的翻译:

public class Main {
    public static void main(String[] args) {
      double x=5.6556464566546546546556465465465;
      float y=(float)x;
      double z=  1+y;
        System.out.println(x+"\n"+y+"\n"+z);
    }
}

以下是您要求的输出部分的翻译:

5.6556464566546545
5.6556463
6.655646324157715

如果您有其他问题或需要进一步帮助,请随时告诉我。

英文:

This is the code

    public static void main(String[] args) {
      double x=5.6556464566546546546556465465465;
      float y=(float)x;
      double z=  1+y;
        System.out.println(x+"\n"+y+"\n"+z);
    }
}

and this is the output

5.6556464566546545
5.6556463
6.655646324157715

I can understand the value of x and y but z from where it got those fractional numbers after the 3??!

Thank you very much

答案1

得分: 1

浮点数是Java中实际数字的近似表示,因为它们存储的方式不同。如果您需要精确的值,请使用BigDecimal

英文:

Floats are an approximation of the actual number in Java, due to the way they're stored. If you need exact values, use a BigDecimal instead.

huangapple
  • 本文由 发表于 2020年8月18日 03:32:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63457471.html
匿名

发表评论

匿名网友

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

确定