2013-10-20 32 views
2

失去精度有在Java中過去的試卷一個問題,我的兄弟:將通過我們的隱式轉換

有了原始數據類型的隱式轉換,你可能會失去精度,並得到不正確的結果。

一個真實的,B假

的關鍵答案是:真正的

我認爲這既不會丟失精度也得到不正確的結果。我知道顯式轉換可能會失去精度並得到不正確的結果,但不是隱含的結果。

例如:

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. 

作爲對筆記狀態:

隱式類型轉換:程序員不作任何嘗試轉換的類型,而所述類型自動地被轉換系統在某些情況下。

任何人都可以請指教?

非常感謝。

+0

理查德所以你的意思是隱式轉換不會失去精度吧?答案是B,錯誤的權利? – bean

+0

隱式轉換是指編譯器通過放入隱式轉換來接受代碼。如果存在編譯錯誤,則不存在轉換。 –

回答

3

在某些情況下,編譯器將允許隱式轉換,但仍可能失去精度。例如:

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

查看JLS瞭解更多詳情。

+0

我還沒有發現這個程序的任何困難 –

+0

@RichardTingle:定義「困難」。 'b'不代表與'a'相同的數值;因此我們失去了精確度。 –

+0

在這個程序中intIn和intOut print 9223372036854775807; Long intIn = Long.MAX_VALUE; System.out.println(intIn); float floatTest = intIn; System.out。的println(floatTest); long intOut =(long)floatTest; System.out.println(intOut); –

6

回答= A

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

輸出

9223372036854775807 
9223372036854776000 
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 ;)