使用浮动而不是双怪时输出 [英] Strange output when using float instead of double

查看:170
本文介绍了使用浮动而不是双怪时输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

奇怪的输出,当我使用浮动而不是双击

Strange output when I use float instead of double

#include <stdio.h>
void main()
{
    double p,p1,cost,cost1=30;
    for (p = 0.1; p < 10;p=p+0.1)
    {
        cost = 30-6*p+p*p;
        if (cost<cost1)
        {
            cost1=cost;
            p1=p;
        }
        else
        {
            break;
        }
        printf("%lf\t%lf\n",p,cost);
    }
    printf("%lf\t%lf\n",p1,cost1);
}

给出输出作为 P = 3预期;

Gives output as expected at p = 3;

但是当我使用浮动的输出是一个有点怪异。

But when I use float the output is a little weird.

#include <stdio.h>
void main()
{
    float p,p1,cost,cost1=40;
    for (p = 0.1; p < 10;p=p+0.1)
    {
        cost = 30-6*p+p*p;
        if (cost<cost1)
        {
            cost1=cost;
            p1=p;
        }
        else
        {
            break;
        }
        printf("%f\t%f\n",p,cost);
    }
    printf("%f\t%f\n",p1,cost1);
}

为什么 P 在第二种情况下2.7后会奇怪增量?

Why is the increment of p in the second case going weird after 2.7?

推荐答案

这是发生因为浮动双击在基地2.大多数基10个数字数据类型存储的数字不能准确地存储。舍入误差时使用浮动取值更加迅速增加。内存有限的嵌入式应用之外,它通常更好,或至少更容易,使用双击因为这个原因。

This is happening because the float and double data types store numbers in base 2. Most base-10 numbers can’t be stored exactly. Rounding errors add up much more quickly when using floats. Outside of embedded applications with limited memory, it’s generally better, or at least easier, to use doubles for this reason.

要看到这种情况出现的双击类型,考虑这code的输出:

To see this happening for double types, consider the output of this code:

#include <stdio.h>
int main(void)
{
    double d = 0.0;
    for (int i = 0; i < 100000000; i++)
        d += 0.1;
    printf("%f\n", d);
    return 0;
}

在我的电脑上,它输出9999999.981129。所以,经过100百万次迭代,舍入误差的结果作出的0.018871的差异。

On my computer, it outputs 9999999.981129. So after 100 million iterations, rounding error made a difference of 0.018871 in the result.

有关浮点数据类型如何工作的更多信息,请阅读的什么每台计算机科学家应该知道关于浮点运算。或者,正如晃的评论中提到,看到href=\"http://floating-point-gui.de/\" rel=\"nofollow\">的

For more information about how floating-point data types work, read What Every Computer Scientist Should Know About Floating-Point Arithmetic. Or, as akira mentioned in a comment, see the Floating-Point Guide.

这篇关于使用浮动而不是双怪时输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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