问题
I were practicing some c programming when I saw this:
#include <stdio.h>
int main (void){
printf("result %.50lf",(double)10.0/10000000.0);
return 0;
}
And the result was 0.00000099999999999999995474811182588625868561393872
Can somebody explain me why happens this?
回答1:
The internal representation of double
is a binary floating-point encoding that cannot precisely represent all (or indeed most) decimal fractions, for the same reason for example 1/3 cannot be exactly represented in decimal, 10.0/10000000.0 cannot be exactly represented in binary.
Moreover 64-bit double precision binary floating point has a precision of around 15 decimal significant figures so attempting to output 50 decimal places is always going to end up in irrelevant and meaningless digits. Your actual result within the precision of a double is 0.000000999999999999999.
See also: What Every Programmer Should Know About Floating-Point Arithmetic
来源:https://stackoverflow.com/questions/29197414/inexact-float-division