简体   繁体   English

浮点变量在C中不会减少-无限while循环

[英]Floating point variable won't decrement in C - infinite while loop

The following code is terrible, but was encountered in a production situation. 以下代码很糟糕,但是在生产环境中遇到过。 It was solved by doing something less insane - but I can't work out why the value remains constant. 它通过做一些不那么疯狂的事情来解决-但我不知道为什么值保持不变。 FWIW this arbitrary large value was taken from a timestamp. FWIW这个任意大的值是从时间戳获取的。

#import <stdio.h>

int main(void)
{
    float wtf =  466056.468750;

    while(wtf > .01)
    {
        wtf -= .01;

        /* other operations here */

        printf("wtf = %f\n", wtf);
    }

    return 0;
}

When the program is run the output produced is 运行程序时,产生的输出为

wtf = 466056.468750 wtf = 466056.468750

wtf = 466056.468750 wtf = 466056.468750

wtf = 466056.468750 wtf = 466056.468750

wtf = 466056.468750 wtf = 466056.468750

wtf = 466056.468750 wtf = 466056.468750

wtf = 466056.468750 wtf = 466056.468750

wtf = 466056.468750 wtf = 466056.468750

wtf = 466056.468750 wtf = 466056.468750

wtf = 466056.468750 wtf = 466056.468750

wtf = 466056.468750 wtf = 466056.468750

When debugging with, I can see that an appropriate value is returned for the expression wtf - .01 but it just doesn't seem to persist. 在进行调试时,我可以看到为wtf - .01返回了一个适当的值,但是它似乎并没有持久。

My question is, why isn't the decremented value stored in the variable? 我的问题是,为什么递减后的值不存储在变量中?

In gdb the value of the operation is printed out as follows 在gdb中,该操作的值打印如下

10          printf("wtf = %f\n", wtf);
(gdb) p wtf
$1 = 466056.469
(gdb) p wtf - .01
$2 = 466056.45874999999
(gdb) n

Whilst there is a clear change in precision, the value 466056.45874999999 is neither 466056.469 nor 466056.468750 (the value printed to the console) 尽管精度有明显变化,但值466056.45874999999既不是466056.469也不是466056.468750(打印到控制台的值)

466056.468750f and 466056.468750f - 0.01f both have the same representation as a float . 466056.468750f466056.468750f - 0.01f都具有与float相同的表示形式。

Floating point numbers have a finite representation. 浮点数具有有限的表示形式。 Multiple real numbers have the same floating point representation. 多个实数具有相同的浮点表示形式。 Floating points are roughly logarithmically spaced and when the floating point number is bigger, there are more and more real numbers that have its same representation. 浮点数大致以对数形式隔开,并且当浮点数较大时,越来越多的实数具有相同的表示形式。

Change the type of wtf from float to double . wtf的类型从float更改为double The float type has no precision for that number (read somewhere the web to understand the differences) Hope I could help! float类型对于该数字没有精度(请在网上阅读以了解差异),希望我能帮上忙!

What's happening with your program is caused by floating point inaccuracy. 您的程序所发生的事情是由浮点错误引起的。 The program will work as you expect if you replace float with double . 如您所愿,如果你更换计划将努力floatdouble

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM