对于float作为计数器的循环,增加0.01,不打印预期的浮点值 [英] For loop with float as counter, increasing by 0.01, does not print expected float values

查看:221
本文介绍了对于float作为计数器的循环,增加0.01,不打印预期的浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(float x = 0.00; x <1.00; x + = 0.01){
cout < x<< ENDL;

$ / code>

我预计

  0.00 
0.01
0.02
...

它可以正常工作,直到 0.83

 0.81 
0.82
0.83
0.839999
0.849999
0.859999
0.869999
0.879999
0.889999
0.899999
0.909999
0.919999
0.929999
0.939999
0.949999
0.959999
0.969999
0.979999
0.989999
0.999999

这部分是怎么回事?为什么所有额外的 9 s?

解决方案

请阅读每个计算机科学家应该知道的关于浮点算术的知识。 p>

浮点类型不能表示每个可能的数值。他们有一些不准确的地方。最接近表示的IEEE754单精度浮点值< 0.84 0.839999973773956298828125 。这比 0.84 少一点。正如你所看到的那样,打印时,显示为 0.839999 。这个数字的二进制表示是:

pre $ 00111111 01010111 00001010 00111101
0.01 也不能完全代表 float x 时,你的期望就变得越来越不精确了。你可以通过使用 int s来避免这种情况,例如:

  for(int x = 0; x <100; x + = 1){
cout< (x / 100.0f)< ENDL;

$ / code>

然而,在执行完毕后,它所打印的许多值仍然不能被表示师。如果你根本不能处理不精确的问题,你就不能使用浮点数值。将值存储为 int s,并简单地将它们解释为表示相应的除以100 float 的值。


for (float x = 0.00; x < 1.00; x += 0.01) {
    cout << x << endl;
}

I expect

0.00
0.01
0.02
...

And it works fine, until 0.83:

...
0.81
0.82
0.83
0.839999
0.849999
0.859999
0.869999
0.879999
0.889999
0.899999
0.909999
0.919999
0.929999
0.939999
0.949999
0.959999
0.969999
0.979999
0.989999
0.999999

What's up with that part? Why all the extra 9s?

解决方案

Please read What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Floating point types can not represent every possible numeric value. They have some imprecision. The closest representable IEEE754 single-precision floating point value to 0.84 is 0.839999973773956298828125. This is a little less than 0.84. As you have seen, when printed, this is shown as as 0.839999. The binary representation of this number is:

00111111 01010111 00001010 00111101

In fact, even 0.01 is not exactly representable with float, so every time you add this value to x, your expectation becomes less and less precise. You can avoid this by using ints instead, like so:

for (int x = 0; x < 100; x += 1) {
    cout << (x / 100.0f) << endl;
}

However, many of the values it prints will still not be representable after performing the division. If you can't deal with imprecision at all, you must simply not work with floating point values. Store your values as ints and simply interpret them as representing the corresponding divided by 100 float value.

这篇关于对于float作为计数器的循环,增加0.01,不打印预期的浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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