将浮点数转换为 int,或将 int 强制转换为浮点数

Cast float to int, or int to float?

本文关键字:转换 int 浮点数 或将      更新时间:2023-10-16

我可以将常量定义为浮点数或 32 位 uint:

const float SecondsPerMinute = 60.0F;

const uint32 SecondsPerMinute = 60U;

常量用于一些需要 int 的方程和一些期望浮点数的方程。我想让我的编译器和静态分析工具满意,所以我会根据需要将其static_cast为适当的类型。

是将 const 定义为浮点数并转换为 int

,还是将其定义为 int 并将其转换为浮点数更好?这有什么不同,还是更多的是个人意见问题?

假设常量作为 int 和浮点数使用次数相等。

模板怎么样:

template <typename T>
constexpr T SecondsPerMinute = T(60);

用法:

std::printf("%d %f", SecondsPerMinute<int>, SecondsPerMinute<double>);