本文介绍了处理浮点数的精度问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有一种方法来克服准确性问题,这似乎是我的机器的浮点数的内部表示的结果:
I was wondering if there is a way of overcoming an accuracy problem that seems to be the result of my machine's internal representation of floating-point numbers:
对于为了清楚起见,问题归纳为:
For the sake of clarity the problem is summarized as:
// str is "4.600"; atof( str ) is 4.5999999999999996
double mw = atof( str )
// The variables used in the columns calculation below are:
//
// mw = 4.5999999999999996
// p = 0.2
// g = 0.2
// h = 1 (integer)
int columns = (int) ( ( mw - ( h * 11 * p ) ) / ( ( h * 11 * p ) + g ) ) + 1;
在转换为整数类型之前,列计算的结果为1.9999999999999996;所以距离所期望的2.0的结果很近。
Prior to casting to an integer type the result of the columns calculation is 1.9999999999999996; so near yet so far from the desired result of 2.0.
任何建议最受欢迎。
推荐答案
将浮点数舍入为整数的非常简单有效的方法:
A very simple and effective way to round a floating point number to an integer:
int rounded = (int)(f + 0.5);
注意:只有 f
总是积极的。 (感谢j随机黑客)
Note: this only works if f
is always positive. (thanks j random hacker)
这篇关于处理浮点数的精度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!