当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ atan2()用法及代码示例


atan2()是C++ STL中的内置函数,它返回(y /x)的正切逆,其中y是y坐标的比例,x是x坐标的比例。数值介于–\pi\pi代表角度\theta(x,y)点和正x轴的角度。它是X轴正方向与点(x,y)之间的逆时针角度(以弧度为单位)。

用法:

atan2(data_type y, data_type x)

参数:该函数接受下面描述的两个强制性参数:


  • y –此值指定y坐标。
  • X -此值指定x坐标。

参数可以是double,float或long double数据类型。

返回值:该函数返回介于–\pi\pi代表角度\theta(x,y)点和正x轴的角度。它是X轴正方向与点(x,y)之间的逆时针角度(以弧度为单位)。

以下示例程序旨在说明atan2()函数:

示例1:

// CPP program to demonstrate the atan2() 
// function when both parameters are of 
// same type 
#include<bits/stdc++.h> 
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; 
}
输出:
atan2(y/x) = 0.785398 radians
atan2(y/x) = 45 degrees

示例2:

// CPP program to demonstrate the atan2() 
// function when both parameters are of 
// different types 
#include <bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    double result; 
    float x = -10.0; 
    int y = 10; 
    result = atan2(y, x); 
  
    cout << "atan2(y/x) = " << result 
         << " radians" << endl; 
    cout << "atan2(y/x) = " << result * 180 / 3.141592 << " degrees" << endl; 
  
    return 0; 
}
输出:
atan2(y/x) = 2.35619 radians
atan2(y/x) = 135 degrees

示例3:

// CPP program to demonstrate the atan2() 
// function when y/x is undefined 
#include<bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    double x = 0.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; 
}
输出:
atan2(y/x) = 1.5708 radians
atan2(y/x) = 90 degrees

示例4:

// CPP program to demonstrate the atan2() 
// function when both parameters are zero 
#include<bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    double x = 0.0, y = 0.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; 
}
输出:
atan2(y/x) = 0 radians
atan2(y/x) = 0 degrees

错误和异常:当字符串或字符作为参数传递时,该函数不返回任何匹配函数来调用错误。
示例5:

// CPP program to demonstrate the atan2() 
// errors and exceptions 
#include<bits/stdc++.h> 
using namespace std; 
  
int main() 
{ 
    double x = 0.0, y = 10.0, result; 
    result = atan2("1", x); 
  
    cout << "atan2(y/x) = " << result << " radians" << endl; 
  
    cout << "atan2(y/x) = " << result * 180 / 3.141592 
         << " degrees" << endl; 
  
    return 0; 
}

输出:

prog.cpp:9:26: error: no matching function for call to 'atan2(const char [2], double&)'
     result = atan2("1", x);


相关用法


注:本文由纯净天空筛选整理自pawan_asipu大神的英文原创作品 atan2() function in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。