当前位置:   article > 正文

C++中浮点数的比较与四舍五入_c++ float 四舍五入

c++ float 四舍五入

浮点数的比较

C/C++浮点数比较时,需要特别注意:计算机中浮点数存储的是近似值,或者更准确的说:除了可以表示为2的幂次以及整数数乘的浮点数可以准确表示外,其余的数的值都是近似值。例如,1.5可以精确表示,因为1.5 = 3*2^(-1);然而3.6却不能精确表示,因为它并不满足这一规则。因此浮点数的比较需要考虑精度问题。
精度由计算过程中需求而定。比如一个常用的精度为1e-6.也就是0.000001.所以对于两个浮点数a,b,如果要比较大小,那么常常会设置一个精度,如果fabs(a-b)<=1e-6,那么就是相等了。
当然,计算机中浮点数本身的精度也可以作为浮点数比较的精度。浮点数精度的设定如下

//定义在float.h
#define DBL_DECIMAL_DIG  17                      // # of decimal digits of rounding precision
#define DBL_DIG          15                      // # of decimal digits of precision
#define DBL_EPSILON      2.2204460492503131e-016 // smallest such that 1.0+DBL_EPSILON != 1.0

#define FLT_DECIMAL_DIG  9                       // # of decimal digits of rounding precision
#define FLT_DIG          6                       // # of decimal digits of precision
#define FLT_EPSILON      1.192092896e-07F        // smallest such that 1.0+FLT_EPSILON != 1.0

#define LDBL_DIG         DBL_DIG                 // # of decimal digits of precision
#define LDBL_EPSILON     DBL_EPSILON             // smallest such that 1.0+LDBL_EPSILON != 1.0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

所以,浮点数的比较大致是这样:

	double f1 = 10, f2 = 10;
	if (fabs(f1 - f2) <= FLT_EPSILON)			//比较两个浮点数是否相等,采用单浮点精度
	{
		//...
	}
	if (f1>f2 && fabs(f1 - f2) > FLT_EPSILON)	//比较一个浮点数是否大于另一个
	{
		//...
	}
	if (f1<f2 && fabs(f1 - f2) > FLT_EPSILON)		//比较一个浮点数是否小于另一个
	{
		//...
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

二 浮点数的四舍五入

浮点数的四舍五入需要自己手写,用到两个全局函数。
floor:不大于浮点数的最大整数;
ceil:不小于浮点数的最小整数。
以下是简单实现。

double round(double r)
{
	return r > 0.0 ? floor(r + 0.5) : ceil(r - 0.5);
}
  • 1
  • 2
  • 3
  • 4
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/302817
推荐阅读
  

闽ICP备14008679号