为什么要从float转换为double来改变值? [英] Why converting from float to double changes the value?

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

问题描述

我一直在试图找出原因,但我不能。
任何人可以帮助我吗?



看下面的例子。

  float f; 

f = 125.32f;
System.out.println(f =+ f)的值;
double d =(double)125.32f;
System.out.println(d =+ d)的值;

这是输出:



f = 125.32



d = 125.31999969482422

解决方案


  1. float 转换为 double 时,不会丢失信息。每个 float 可以表示为一个 double

  2. 另一个手,由 System.out.println 打印的小数表示法是数字的确切值。精确的十进制表示可能需要高达约760个十进制数字。相反, System.out.println 打印出正确的小数位数,允许将十进制表示法解析为原始 float double 。有更多的 double s,所以当打印一个时, System.out.println 需要在表示之前打印更多的数字变得明确。


I've been trying to find out the reason, but I couldn't. Can anybody help me?

Look at the following example.

    float f;

    f = 125.32f;
    System.out.println("value of f = " + f);
    double d = (double) 125.32f; 
    System.out.println("value of d = " + d);

This is the output:

value of f = 125.32

value of d = 125.31999969482422

解决方案

  1. When you convert a float into a double, there is no loss of information. Every float can be represented exactly as a double.
  2. On the other hand, neither decimal representation printed by System.out.println is the exact value for the number. An exact decimal representation could require up to about 760 decimal digits. Instead, System.out.println prints exactly the number of decimal digits that allow to parse the decimal representation back into the original float or double. There are more doubles, so when printing one, System.out.println needs to print more digits before the representation becomes unambiguous.

这篇关于为什么要从float转换为double来改变值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆