C++ cmath atan2() 函数

定义和用法

atan2() 函数返回从直角坐标系 (x, y) 转换到极坐标系 (r, theta) 中的角度 theta,以弧度表示。

这与调用 atan(y/x) 相同,不同之处在于它考虑了 x 的负值,因此可以返回 -PI/2 到 PI/2 范围之外的角度。

atan2() 函数定义在 <cmath> 头文件中。

注意:atan2() 方法中,y 坐标在前,然后是 x 坐标。这是因为它相当于 y/x 除法的反正切。

实例

给定直角坐标,返回极坐标中的角度(以弧度表示):

cout << atan2(0.5, 0.5);
cout << atan2(-0.5, -0.5);
cout << atan2(5, 5);
cout << atan2(10, 20);
cout << atan2(5, -5);
cout << atan2(-10, 10);

亲自试一试

语法

以下之一:

atan2(double y, double x);
atan2(float y, float x);

参数

参数 描述
y

必需。要查找角度的点的 y 坐标。

如果这是整数类型,则将被视为 double 类型。

x

必需。要查找角度的点的 x 坐标。

如果这是整数类型,则将被视为 double 类型。

技术细节

返回:

如果所有参数都是 float 类型,则返回 float 值。

在其他情况下,返回 double 值,表示点 (x, y) 绕原点 (0, 0) 形成的角度(以弧度计)。