C - 印刷中的双精度50个有效数字产生不准确的值 [英] Double precision in C - printing 50 significant figures yields inaccurate values
问题描述
#include< stdio.h>
#include< stdlib.h>
#include< math.h>
int main(int argc,char ** argv){
double x = 2.0 / 20.0;
printf(%1.50f \\\
,x);
return(EXIT_SUCCESS);
}
该程序给了我:0.10000000000000000555111512312578270211815834045410。我的问题:为什么会发生这种情况?我该怎么解决这个问题?或至少舍入〜15位小数位数?
感谢您的帮助。
浮点数的基础:
http://en.wikipedia.org/wiki/Floating_point
您的案例中的答案 0.10
不能在二进制浮点数中表示。因此,只有16位数字才能正确。但是,您尝试将其打印到50位小数位。
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.
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.
这篇关于C - 印刷中的双精度50个有效数字产生不准确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!