Monday, December 11, 2017

C++11: std::nearbyint()

C++11 added the std::nearbyint() function. Here is an example:

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

int main()
{
  cout << nearbyint(0.0) << " "; //  0
  cout << nearbyint(0.5) << " "; //  0
  cout << nearbyint(1.5) << " "; //  2
  cout << nearbyint(2.0) << " "; //  2
  cout << nearbyint(2.5) << " "; //  2

  cout << ": ";

  cout << nearbyint(-0.0) << " "; // -0
  cout << nearbyint(-0.5) << " "; // -0
  cout << nearbyint(-1.5) << " "; // -2
  cout << nearbyint(-2.0) << " "; // -2
  cout << nearbyint(-2.5) << " "; // -2

  cout << endl;
  return 0;
}
// Output: 0 0 2 2 2 : -0 -0 -2 -2 -2
Reference: http://en.cppreference.com/w/cpp/numeric/math/nearbyint

No comments:

Post a Comment