Loss of precision on adding doubles?

亡梦爱人 提交于 2019-12-19 11:21:34

问题


folks! I've encountered a little problem: I'm doing a simple addition with three double values. The result has a smaller precision than the used values.

double minutes = 3;
minutes = minutes / (24.0*60.0);  // contains 0.00208333
double hours = 3;
hours = hours / 24.0; // contains 0.125
double days = 3; // contains 3 

double age = days + hours + minutes; // result is 3.12708 

I found no way to avoid this behaviour.


回答1:


Nothing seems to be wrong with the calculation as what the comments on your post said.

If you'd like to see more precision consider looking up setprecision()




回答2:


There is no problem. The significant figure of 0.00208333 and 3.12708 are both 6. This is a correct result.




回答3:


Sometimes in order to get the value according to the desired precision we have to specify the limit of precision,here is my code which works fine ,hope it helps:

double minutes = 3;
minutes = minutes / (24.0*60.0);
double hours = 3;
hours = hours / 24.0; 
double days = 3;
double age = days + hours + minutes;
printf("%.8f",age);//here i have included the places of precision (.8)


来源:https://stackoverflow.com/questions/17213485/loss-of-precision-on-adding-doubles

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