English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ atan2Usage and example of the function

C++ Library Function <cmath>

C ++The atan function2The function returns the arctangent of the coordinates in radians.

This function returns<cmath>defined in the header file.

tan-1(y/x) = atan2(y, x)

atan2The prototype[from C ++ 11Standard library]

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 the combination of arithmetic types.

atan2The parameters

The atan function2The function has two parameters: 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.

atan2The return value

atan2The function returns[-π, π]Values in the range. If both x and y are zero, then atan2The function will return 0.

Example1: atan2How to work with x and y of the same type?

#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 running the program, the output is:

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

Example2: atan2How to use 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 the result in degrees
  cout << "atan2(y/x) = " << result*180/PI << " degrees";
  return 0;
}

When running the program, the output is:

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

  C++ Library Function <cmath>