• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

    最終更新日時(UTC):
    が更新

    履歴 編集

    function
    <cmath>

    std::fabs

    namespace std {
      float fabs(float x);              // (1) C++03からC++20まで
      double fabs(double x);            // (2) C++03からC++20まで
      long double fabs(long double x);  // (3) C++03からC++20まで
    
      constexpr floating-point-type
        fabs(floating-point-type x);    // (4) C++23
    
      double
        fabs(Integral x);               // (5) C++11
      constexpr double
        fabs(Integral x);               // (5) C++23
    
      float
        fabsf(float x);                 // (6) C++17
      constexpr float
        fabsf(float x);                 // (6) C++23
    
      long double
        fabsl(long double x);           // (7) C++17
      constexpr long double
        fabsl(long double x);           // (7) C++23
    }
    

    概要

    算術型の絶対値を求める。

    戻り値

    引数 x の絶対値を返す。

    x±∞ だった場合 +∞ を返す。

    備考

    #include <cmath>
    #include <limits>
    #include <iostream>
    
    int main() {
      std::cout << std::fixed;
      std::cout << "fabs(1.5)  = " << std::fabs(1.5) << std::endl;
      std::cout << "fabs(-1.5) = " << std::fabs(-1.5) << std::endl;
      std::cout << "fabs(0.0)  = " << std::fabs(0.0) << std::endl;
      std::cout << "fabs(-0.0) = " << std::fabs(-0.0) << std::endl;
      std::cout << "fabs(+∞)   = " << std::fabs(std::numeric_limits<double>::infinity()) << std::endl;
      std::cout << "fabs(-∞)   = " << std::fabs(-std::numeric_limits<double>::infinity()) << std::endl;
    }
    

    出力例

    fabs(1.5)  = 1.500000
    fabs(-1.5) = 1.500000
    fabs(0.0)  = 0.000000
    fabs(-0.0) = 0.000000
    fabs(+∞)   = inf
    fabs(-∞)   = inf
    

    バージョン

    言語

    • C++03

    処理系

    • Clang: 1.9 , 2.9 , 3.1
    • GCC: 3.4.6 , 4.2.4 , 4.3.5 , 4.4.5 , 4.5.1 , 4.5.2 , 4.6.1 , 4.7.0
    • ICC: 10.1 , 11.0 , 11.1 , 12.0
    • Visual C++: 2003 , 2005 , 2008 , 2010

    備考

    特定の環境では、早期に constexpr 対応されている場合がある:

    • GCC 4.6.1 以上

    実装例

    namespace std {
      float fabs(float x) {
        return signbit(x) ? -x : x;
      }
    
      double fabs(double x) {
        return signbit(x) ? -x : x;
      }
    
      long double fabs(long double x) {
        return signbit(x) ? -x : x;
      }
    
      template<class Integral>
      typename enable_if<is_integral<Integral>::value, double>::type
      fabs(Integral x) {
        return fabs(static_cast<double>(x));
      }
    }
    

    参照