what is -0.0000 in c when using floats and double?

喜你入骨 提交于 2019-12-24 00:38:35

问题


#include <stdio.h>
#include <stdlib.h>

#define answer 3.141593

void main(int argc, char **argv) {

        float a = (argc - 2)?: strtod(argv[1], 0);    
        printf("double = %lf ,float =  %f", a-answer , a-answer);

}

when I run it like that:

./a.out 3.141593

the output is

double = -0.000000 ,float =  -0.000000

Why does it -0.00000 ? how can I make it output 0.000000 ?

How can I make a == answer ?


How comes there is -0 value if it uses 2's complement?


回答1:


Floating point numbers doesn't use 2's complement. They have sign, exponent and mantissa and your numbers have just zero with sign, or more probably, you have some number like -1.0e-15, which is printed as -0.0000. try %e instead of %f. The small difference is made by inability to store numbers with infinte precission in finite precission data type (some rounding occured) and when you change double to float, additional rounding have to occur. (take in mind, that 3.141593 is infinite periodic number in binary representation, this it really depends on in which type is this number stored)



来源:https://stackoverflow.com/questions/15175218/what-is-0-0000-in-c-when-using-floats-and-double

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!