代码之家  ›  专栏  ›  技术社区  ›  math

When do I use fabs and when is it sufficient to use std::abs?

  •  91
  • math  · 技术社区  · 16 年前

    我认为 abs 和 fabs are behaving different when using math.h . But when I use just cmath 和 std::abs , do I have to use std::fabs 或 法布斯 ?Or isn't this defined?

    4 回复  |  直到 9 年前
        1
  •  116
  •   Mike Seymour    16 年前

    在C++中,使用总是足够的。 std::abs ; it's overloaded for all the numerical types.

    在C中, abs only works on integers, and you need fabs 对于浮点值。这些在C++中是可用的(连同所有的C库),但是不需要使用它们。

        2
  •  22
  •   Alan Turing    13 年前

    It's still okay to use fabs 对于 double 和 float std:: 关闭 abs , that the behavior remains the same for floating point inputs.

    我只花了10分钟调试这个问题,因为我自己使用的错误。 防抱死制动系统 而不是 std::abs . I assumed that the using namespace std; 会推断 性病::ABS

    不管怎样,我相信它很好用 法布斯 而不是 防抱死制动系统 for floating-point inputs as a way of documenting your intention clearly.

        3
  •  8
  •   Kenichi Hidai    10 年前

    There is one more reason to recommend std::fabs

    If you forget to include <cmath>, your std::abs(my_float_num) 可以是 std::abs(int) 而不是 std::abs(float) . 很难注意到。

        4
  •  1
  •   BS3    9 年前

    “ABS”和“FAB”对于C++浮点类型来说是相同的,它们可以在没有模糊的过载消息的情况下进行翻译。

    Together with template usage and especially when using mpreal there are cases with hard "ambiguous overload" messages - abs(static_cast<T>(x)) isn't always solving that. 当abs模棱两可时,fabs有可能按预期工作。对斯奎特来说,我没有找到这么简单的逃跑方式。

    几个星期以来,我一直在努力克服C++的“不存在的问题”。我正在更新一个旧的C++程序到C++ 14,以获得比以前更好和更好的模板使用。通常,同一个模板参数可以是实际的任何标准float、复杂类型或类类型。为什么,长双比其他类型更明智。 然后,我将默认的float类型设置为mpreal,得到了大量的语法错误。 这导致了数千个不明确的过载,例如abs和sqrt,需要不同的解决方案。有些人需要重载的帮助函数,但在模板之外。必须用零或一个或一个类型的常量类型分别替换千种0.0升和1.0升的用法-由于模棱两可,无法进行自动转换定义。

    Up to May I found the existing of implicit conversions very nice. 但更简单的是,如果没有任何类型,那么使用安全的显式类型将typesave常量强制转换为任何其他标准常量类型。

    推荐文章