double / float的C ++内部表示 [英] C++ internal representation of double/float

查看:186
本文介绍了double / float的C ++内部表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解为什么C ++分区的行为方式。我有一个简单的程序,将1除以10(使用VS 2003)

I am unable to understand why C++ division behaves the way it does. I have a simple program which divides 1 by 10 (using VS 2003)

double dResult = 0.0;
dResult = 1.0/10.0;

我期望dResult为0.1,但我得到0.10000000000000001

I expect dResult to be 0.1, However i get 0.10000000000000001


  1. 为什么我得到这个值,double / float的内部表示有什么问题

  2. 如何获得正确的值?

感谢。

推荐答案

因为 all 大多数现代处理器使用二进制浮点,它不能精确表示0.1(没有办法代表0.1 m * 2 ^ e 与整数 m e )。

Because all most modern processors use binary floating-point, which cannot exactly represent 0.1 (there is no way to represent 0.1 as m * 2^e with integer m and e).

想要查看正确的值,可以使用以下命令打印:

If you want to see the "correct value", you can print it out with e.g.:

printf("%.1f\n", dResult);

这篇关于double / float的C ++内部表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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