为什么从 float 转换为 double 会改变值?

时间:2022-11-07
本文介绍了为什么从 float 转换为 double 会改变值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我一直在试图找出原因,但我找不到.有人可以帮帮我吗?

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 再现传递给 printlndouble 的值.

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 会改变值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!