問題描述
我一直在試圖找出原因,但我找不到.有人可以幫幫我嗎?
I've been trying to find out the reason, but I couldn't. Can anybody help me?
看下面的例子.
float f = 125.32f;
System.out.println("value of f = " + f);
double d = (double) 125.32f;
System.out.println("value of d = " + d);
這是輸出:
value of f = 125.32
value of d = 125.31999969482422
推薦答案
float
的值在轉換為 double
時不會改變.顯示的數字有所不同,因為需要更多數字來區分 double
值與其相鄰值,即 Java 文檔要求.那是 toString
的文檔,從 println
的文檔中引用(通過幾個鏈接).
The value of a float
does not change when converted to a double
. There is a difference in the displayed numerals because more digits are required to distinguish a double
value from its neighbors, which is required by the Java documentation. That is the documentation for toString
, which is referred (through several links) from the documentation for println
.
125.32f
的確切值是 125.31999969482421875.兩個相鄰的 float
值是 125.3199920654296875 和 125.32000732421875.觀察到 125.32 比任何一個鄰居都更接近 125.31999969482421875.因此,通過顯示125.32",Java 顯示了足夠的數字,以便從十進制數字轉換回 float
再現了傳遞給 println<的
float
的值/代碼>.
The exact value for 125.32f
is 125.31999969482421875. The two neighboring float
values are 125.3199920654296875 and 125.32000732421875. Observe that 125.32 is closer to 125.31999969482421875 than to either of the neighbors. Therefore, by displaying "125.32", Java has displayed enough digits so that conversion back from the decimal numeral to float
reproduces the value of the float
passed to println
.
在兩個相鄰<代碼>雙代碼>的125.3199996948242的 1875 強>是125.3199996948242的 045391452847979962825775146484375 并125.3199996948242的 329608547152020037174224853515625 即可.值結果觀察到 125.32 更接近后一個鄰居而不是原始值 (125.31999969482421875).因此,打印125.32"不包含足夠的數字來區分原始值.Java 必須打印更多的數字,以確保從顯示的數字轉換回 double
再現傳遞給 println
的 double
的值.
The two neighboring double
values of 125.31999969482421875 are 125.3199996948242045391452847979962825775146484375 and 125.3199996948242329608547152020037174224853515625.
Observe that 125.32 is closer to the latter neighbor than to the original value (125.31999969482421875). Therefore, printing "125.32" does not contain enough digits to distinguish the original value. Java must print more digits in order to ensure that a conversion from the displayed numeral back to double
reproduces the value of the double
passed to println
.
這篇關于為什么從 float 轉換為 double 會改變值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!