Monday, December 11, 2017

C++11: std::copysign() and std::signbit()

C++11 added the functions std::copysign() and std::signbit(). Here is an example:

#include <cmath>
#include <iostream>
using namespace std;

int main()
{
  cout << copysign(-11.0,  99.0) << " "; //  11
  cout << copysign(-11.0, -99.0) << " "; // -11
  cout << copysign( 11.0,  99.0) << " "; //  11
  cout << copysign( 11.0, -99.0) << " "; // -11

  cout << ": ";

  cout << signbit( 0.0) << " "; // 0
  cout << signbit(-0.0) << " "; // 1
  cout << signbit( 9.0) << " "; // 0
  cout << signbit(-9.0) << " "; // 1

  cout << endl;
  return 0;
}
// Output: 11 -11 11 -11 : 0 1 0 1
References:
http://en.cppreference.com/w/cpp/numeric/math/copysign
http://en.cppreference.com/w/cpp/numeric/math/signbit

No comments:

Post a Comment