【问题标题】:will we loose precision by implicit conversion我们会通过隐式转换来降低精度吗
【发布时间】:2013-10-20 15:35:17
【问题描述】:

Java 过去的试卷中有一道题是我的兄弟:

使用原始数据类型的隐式转换,您可能会丢失精度并得到不正确的结果。

A 真,B 假

答案的关键是A:是的

我认为它既不会丢失精度也不会得到错误的结果。我知道显式转换可能会丢失精度并得到不正确的结果,但不是隐式转换。

例如:

int i = 9;

short s = 3;

i = s; // implicit conversion, neither loose 
      //precision nor incorrect results

s = i; // compile error, do we call this implicit conversion? 
       //if yes, then the answer to question 3 is True, 
       //but I don't think this is an implicit conversion, 
       //so I think answer is false.   

如注释中所述:

隐式类型转换:程序员不尝试转换类型,而是在某些情况下由系统自动转换类型。

谁能给点建议?

非常感谢。

【问题讨论】:

  • Richard 所以你的意思是隐式转换不会失去精度吧?答案是 B,是假的吧?
  • 隐式转换是指编译器通过进行隐式转换来接受代码。如果有编译错误,则没有转换。

标签: java implicit-conversion implicit


【解决方案1】:

答案 = A

    float f = Long.MAX_VALUE;
    System.out.println(Long.MAX_VALUE);
    System.out.printf("%.0f", f);

输出

9223372036854775807
9223372036854776000

【讨论】:

    【解决方案2】:

    在某些情况下,编译器会允许隐式转换,但您仍可能会丢失精度。例如:

    long a = Long.MAX_VALUE;  // 9223372036854775807
    double b = a;             // 9223372036854776000
    

    请参阅JLS 了解更多详情。

    【讨论】:

    • 我没有发现这个程序有任何困难
    • @RichardTingle:定义“困难”。 ba 代表的数值不同;因此我们失去了精确度。
    • 在这个程序中 intIn 和 intOut 打印 9223372036854775807;长 intIn=Long.MAX_VALUE; System.out.println(intIn);浮动浮动测试=intIn; System.out.println(floatTest);长 intOut=(long)floatTest; System.out.println(intOut);
    • 我知道第二次转换是明确的,但如果有任何事情会使事情变得更糟
    • 然而 Evgeniy Dorofeev 的程序有问题(失去精度)。也许我的 JVM 很“聪明”
    【解决方案3】:

    赋值运算符中有隐式转换。这些可能会丢失精度或导致溢出。对于常规赋值,隐式转换仅在编译器知道它是安全的时候才会发生。它仍然会丢失精度,但不会导致溢出。

    例如

    final int six = 6;
    byte b = six; // compiler uses constant propagation and value is in range.
    
    int five = 5;
    byte b2 = five; // fails to compile
    
    double d = 5.5;
    five += d; // compiles fine, even though implicit conversion drops the 0.5
    // five == 10 not 10.5
    
    five += Double.NaN; // five is now 0 ;)
    

    【讨论】:

      猜你喜欢
      • 2016-06-18
      • 2017-10-23
      • 2022-11-02
      • 2011-07-16
      • 2017-04-11
      • 1970-01-01
      • 1970-01-01
      • 2022-08-06
      • 1970-01-01
      相关资源
      最近更新 更多