浮点不准确 [英] Floating point inaccuracies

查看:94
本文介绍了浮点不准确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写一个函数时,我会在一个范围内的每个数字执行一些操作,我遇到浮点不准确的一些问题。问题可以在下面的代码中看到:

While writing a function which will perform some operation with each number in a range I ran into some problems with floating point inaccuracies. The problem can be seen in the code below:

#include <iostream>

using namespace std;

int main()
{
    double start = .99999, end = 1.00001, inc = .000001;
    int steps = (end - start) / inc;

    for(int i = 0; i <= steps; ++i)
    {
        cout << (start + (inc * i)) << endl;
    }
}

问题是上述程序输出的数字像这样:

The problem is that the numbers the above program outputs look like this:

0.99999
0.999991
0.999992
0.999993
0.999994
0.999995
0.999996
0.999997
0.999998
0.999999
1
1
1
1
1
1.00001
1.00001
1.00001
1.00001
1.00001
1.00001


推荐答案

它们只是看起来是正确的,直到第一个1.什么是正确的方法来解决这个问题? >

由于 ostream 默认舍入,您的示例输出只有错误。您可以设置 precision 获取其他输出。

Your sample output only looks wrong because of how ostream rounds by default. You can set precision to get some other output.

cout.precision(10);
cout << (start + (inc * i)) << endl;

这是我现在得到的:

0.99999
0.999991
0.999992
0.999993
0.999994
0.999995
0.999996
0.999997
0.999998
0.999999
1
1.000001
1.000002
1.000003
1.000004
1.000005
1.000006
1.000007
1.000008
1.000009
1.00001

这篇关于浮点不准确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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