可能重複:
Varying behavior for possible loss of precisionJava打破強大的打字!誰能解釋它?
我發現Java的強類型檢查的不一致在編譯時。 請看下面的代碼:
int sum = 0;
sum = 1; //is is OK
sum = 0.56786; //compile error because of precision loss, and strong typing
sum = sum + 2; //it is OK
sum += 2; //it is OK
sum = sum + 0.56787; //compile error again because of automatic conversion into double, and possible precision loss
sum += 0.56787; //this line is does the same thing as the previous line, but it does not give us a compile error, and javac does not complain about precision loss etc.
誰能解釋一下?這是已知的錯誤還是期望的行爲? C++給出了一個警告,C#給出了一個編譯錯誤。
Java打破強打字嗎? 您可以將+ =替換爲 - =或* = - 編譯器可以接受一切。
奇怪的是,你是存儲浮在int變量 –
@ KarelFrajtak沒有修飾符的十進制數(如'd'或'f')是雙精度數,而不是浮點數。此外,我想你可能會錯過這一點.. – nfechner
Java在這裏明顯犯了一個錯誤。在允許沉默演員時,他們應該更加精確。而這個原因造成了另一個糟糕的決定。關於integeral類型操作的規範是一團糟。 – irreputable