浮动没有添加?

0 c floating-point addition

我正在设计一个程序来计算和显示当前人口达到80亿之前的秒数.我认为我的逻辑是合理的,但我的while循环无限循环,我无法弄清楚为什么.

我已经习惯了C++,但这是我第一次用C语言编写,所以我想知道是否存在一些我缺少的语法问题.

// Program to calculate population increase
// to see how many seconds from now
// the population will hit 8 billion

#include <stdio.h>
#include <math.h>

int main()
{
    float currentPop = 7600000000.0;
    float increasePerSec = 2.5;
    int secondCount = 0;

    printf("Counting...\n");

    while (currentPop < 8000000000.01)
    {
        currentPop += increasePerSec;
        secondCount++;
    }
    printf("It will be %f seconds from now.\n",secondCount);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

看起来这个问题存在于这一行:

currentPop += increasePerSec;
Run Code Online (Sandbox Code Playgroud)

因为价值总是保持在76亿.以防我尝试:

currentPop = currentPop + increasePerSec;
Run Code Online (Sandbox Code Playgroud)

同样,但结果没有变化.

Eri*_*hil 7

floatIEEE-754基本32位二进制格式的最常用格式中,7600000000附近的可表示值是7599999488,7600000000和7600000512.这是因为32位格式仅对有效数字使用24位(分数部分) .要表示7600000000,必须设置指数使得有效数的高位表示4294967296(2 32),这意味着低位表示512(2 9).因此,此时可表示数字的增量以512为单位出现.

当您添加2.5到7600000000时,数学结果7600000002.5将四舍五入到最接近的可表示值,因此最终结果为7600000000.

在最常用的格式中double,有效数据有53位,因此具有一半(2 -1)的数字可以表示为2 53(9007199254740992).

注意:此答案假设使用了常见格式.如果需要更高的可移植性,C实现提供有关其浮点信息的信息<float.h>.该信息可用于测试这些floatdouble格式是否提供足够的精度.