简体   繁体   中英

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

#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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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