为什么这个浮点数有2个不同的值?

时间:2018-06-17 06:23:00

标签: c floating-point int

当我这样做时:

float add=0;

int count[] = {3, 2, 1, 3, 1, 2, 3, 3, 1, 2, 1}
for (int i=0; i<11; i++)
    add += 1 / ((float)count+1);

输出结果为:

4.00000000000000000000

但是当我这样做时:

float add=0;

int count[] = {3, 2, 1, 3, 1, 2, 3, 3, 1, 2, 1}
for (int i=0; i<11; i++)
    add += 1.0 / ((float)count+1);

输出结果为:

3.99999976158142089844

当我需要将一个int转换成一个浮点数时,我要么在前面添加(float),要么让它用一个小数运算,例如a / 1.0。有什么区别吗?

编辑: 添加所需的行为。

原因是之后,我需要一个结果,将add添加到int输出的另一个int变量中。但是,当我以第二种方式执行时,int使用3而不是4,所以我想知道第一个和第二个代码之间的区别。

1 个答案:

答案 0 :(得分:4)

您的代码不是C,但这是:

#include <stdio.h>

int main ()
{
        float add = 0;
        int count[] = { 3, 2, 1, 3, 1, 2, 3, 3, 1, 2, 1 };
        for (int i = 0; i < 11; i++) {
                add += 1 / ((float) count[i] + 1);
        }
        printf("%f\n", add);
        return 0;
}

我已使用add += 1 / ((float) count[i] + 1);add += 1.0 / ((float) count[i] + 1);执行此代码。

在这两种情况下,printf("%f\n", add);都会打印4.000000

但是,当我打印变量add的每一位时,它会给我01000000011111111111111111111111(3.9999998)和01000000100000000000000000000000(4)

正如phuclv所指出的,这是因为1.0double,因此计算是以双精度完成的,而使用1时,计算是使用单精度完成的(因为演员要漂浮了。)

如果您在第一个等式中将强制转换替换为double,或者在第二个等式中将1.0更改为1.0f,则您将获得相同的结果。

相关问题