代码之家  ›  专栏  ›  技术社区  ›  C. Korb

将float转换为int,还是将int转换为float?

  •  5
  • C. Korb  · 技术社区  · 8 年前

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

    const float SecondsPerMinute = 60.0F;
    

    const uint32 SecondsPerMinute = 60U;
    

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

    是将常量定义为float并转换为int,还是将其定义为int并转换为float?这会有什么不同吗,还是更多的是个人意见的问题?

    假设常量被用作int和float的次数相等。

    1 回复  |  直到 8 年前
        1
  •  12
  •   Kerrek SB    8 年前

    模板如何:

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

    用法:

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