C++ atan2()

The atan2() function in C++ returns the inverse tangent of a coordinate in radians.

This function is defined in <cmath> header file.


[Mathematics] tan-1(y/x) = atan2(y, x) [In C++ Programming]

atan2() prototype [As of C++ 11 standard]

double atan2(double y, double x);
float atan2(float y, float x);
long double atan2(long double y, long double x);
double atan2(Type1 y, Type2 x); // For combinations of arithmetic types.

atan2() Parameters

The function atan2() takes two arguments: x-coordinate and y-coordinate.

  • x - this value represents the proportion of the x-coordinate.
  • y - this value represents the proportion of the y-coordinate.

atan2() Return value

The atan2() function returns the value in the range of [-π, π]. If both x and y are zero, the atan2() function returns 0.


Example 1: How atan2() works with same type of x and y?

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
  double x = 10.0, y = -10.0, result;
  result = atan2(y, x);
  
  cout << "atan2(y/x) = " << result << " radians" << endl;
  cout << "atan2(y/x) = " << result*180/3.141592 << " degrees" << endl;
  
  return 0;
}

When you run the program, the output will be:

atan2(y/x) = -0.785398 radians
atan2(y/x) = -45 degrees

Example 2: How atan2() works with different types of x and y?

#include <iostream>
#include <cmath>
#define PI 3.141592654

using namespace std;

int main()
{
  double result;
  float x = -31.6;
  int y = 3;
  
  result = atan2(y, x);
  
  cout << "atan2(y/x) = " << result << " radians" << endl;
  
  // Display result in degrees
  cout << "atan2(y/x) = " << result*180/PI << " degrees";

  return 0;
}

When you run the program, the output will be:

atan2(y/x) = 3.04694 radians
atan2(y/x) = 174.577 degrees