这是我想做的:
Take a double (which is between -1 and 1) and cast it to a float. But I want to make sure that the float is ALWAYS less than the double.
有什么简单的方法可以做到这一点吗?
作为引用,这是我想出的一些东西。
float DoubleToSmallerFloat (double X) // ex. X = 0.79828470019999997
{
float Y = X; // 0.79828471 -> note this is greater than X
double Diff = X - Y;
return Y - Abs (Diff) * 10;
}
最佳答案
如果您能够使用 C++11,那么您可以使用 nextafter()
为此:
float doubleToSmallerFloat(double x) {
float f = x;
return f < x ? f : nextafter(f, -1.0f);
}
关于c++ - 确保 float 小于 double C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38904992/