问题
I'm doing an integration program with Riemann sums for my Calculus class. I've decided to use C when computing my integrals, and I noticed a huge error in my program that derives from this problem.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char** argv) {
double x = 2.0/20.0;
printf("%1.50f \n", x);
return (EXIT_SUCCESS);
}
The program gives me : 0.10000000000000000555111512312578270211815834045410. My question: Why does this happen? And how can I fix this? Or at least round off to ~15 decimal places?
Thanks for the help.
回答1:
The basics of floating-point:
http://en.wikipedia.org/wiki/Floating_point
The answer in your case 0.10
is not exactly representable in binary floating-point. Therefore, it's only accurate to about 16 digits. Yet you are trying to print it out to 50 decimal places.
回答2:
If you need more accurate results that what double
can offer, then you may want to check out some of the arbitrary precision libraries that are available.
来源:https://stackoverflow.com/questions/7816504/double-precision-in-c-printing-50-significant-figures-yields-inaccurate-values