C++ atan2()

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

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

示例

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

int main() {

// get the value of tan-1(5.0 / 2.0) cout << atan2(5.0, 2.0);
return 0; } // Output: 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);

// for combinations of arithmetic types
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);
// convert result to degrees double degree = result * (180 / 3.141592); cout << "atan2(y/x) = " << result << " radians" << endl; cout << "atan2(y/x) = " << degree << " degrees"; return 0; }

输出

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

示例 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;
  
// atan2() with float and int arguments 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; }

输出

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

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战