[英]Best way to approximate in direction to zero in C++
I have some troubles explaining clearly but it's rather simple.. 我有一些麻烦解释清楚,但它很简单..
I have a double named value in my C++ program and I want to Floor it if it's a positive value and Ceil if it's a negative value, the precision is given by an external variable. 我在我的C ++程序中有一个双重命名值,如果它是一个正值,我想要它,如果它是负值,我想要Ceil,精度由外部变量给出。
An example: 一个例子:
precision is of 1000 value is 0.2659 so approximated value is 0.265 精度为1000的值为0.2659,因此近似值为0.265
value is -0.2659 so approximated value is -0.265 值为-0.2659,因此近似值为-0.265
I have wrote a simple code but I was wondering if there was a more simple or/and way to do it. 我写了一个简单的代码,但我想知道是否有更简单或/和方式来做到这一点。
Here what I have so far: 到目前为止我所拥有的:
void NodeImpl::approximation(double& value, const double& precision)
{
if (value > 0.0)
{
value = std::floor(value * precision);
}
else
{
value = std::ceil(value * precision);
}
value /= precision;
}
I have wrote a simple code but I was wondering if there was a more simple or/and way to do it. 我写了一个简单的代码,但我想知道是否有更简单或/和方式来做到这一点。
你可以使用std::trunc
:
return std::trunc(value * precision) / precision;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.