2

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.   

如注释所述:

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

有人可以建议吗?

非常感谢。

4

3 回答 3

6

答案 = A

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

输出

9223372036854775807
9223372036854776000
于 2013-10-20T15:44:40.527 回答
3

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

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

有关这方面的更多详细信息,请参阅JLS

于 2013-10-20T15:39:23.640 回答
1

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

例如

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 ;)
于 2013-10-20T15:47:11.310 回答