c++ - 确保 float 小于 double C++

标签 c++ floating-point

这是我想做的:

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/

相关文章:

c++ - 更新到macOS Catalina后无法使用C++代码编译R软件包

python - 浮点表示的模拟

c++ - 用时间检查数据?

c++, c++11, std::atomic 成员函数

c++ - 您对这个 C++ 表达式有什么期望?

python - 如何避免使用 numpy.round 进行不正确的舍入?

c++ - 有效地将两个整数 x 和 y 转换为 float x.y

java - 两条线会在笛卡尔平面相交吗

java - 有没有比 Math.pow 更好(更正确)的方法来计算某些幂的模数?

c++ - 为什么 const ref 返回的 vector<int> 变量不起作用