跳到主要内容

C++ atan2() 二参数反正切函数

C++ 中的 atan2() 函数返回坐标的反正切值,以弧度表示。它定义在 cmath 头文件中。

数学上,atan2(y, x) = tan-1(y/x)

示例

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

int main() {

// 获取 tan-1(5.0 / 2.0) 的值
cout << atan2(5.0, 2.0);

return 0;
}

// 输出:1.19029

atan2() 语法

atan2() 函数的语法是:

atan2(double y, double x);

atan2() 参数

atan2() 函数接受以下参数:

  • x - 表示 x 坐标比例的浮点数
  • y - 表示 y 坐标比例的浮点数

atan2() 返回值

atan2() 函数返回:

  • [-π, π] 范围内的浮点值。
  • 如果 xy 都为零,则返回 0

atan2() 函数原型

cmath 头文件中定义的 atan2() 函数原型是:

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);

示例 1:C++ atan2()

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

int main() {
double x = 10.0, y = -10.0;

double result = atan2(y, x);

// 将结果转换为度
double degree = result * (180 / 3.141592);

cout << "atan2(y/x) = " << result << " 弧度" << endl;
cout << "atan2(y/x) = " << degree << " 度";

return 0;
}

输出

atan2(y/x) = -0.785398 弧度
atan2(y/x) = -45

示例 2:C++ atan2() 使用不同类型

在这个程序中,我们将使用不同数据类型的参数调用 atan2() 函数。

#include <iostream>
#include <cmath>
#define PI 3.141592654
using namespace std;

int main() {
double result;
float x = -31.6;
int y = 3;

// 使用 float 和 int 参数的 atan2()
result = atan2(y, x);

cout << "atan2(y/x) = " << result << " 弧度" << endl;

// 以度显示结果
cout << "atan2(y/x) = " << result * (180 / PI) << " 度";

return 0;
}

输出

atan2(y/x) = 3.04694 弧度
atan2(y/x) = 174.577