如何在C++中利用atan2函數(shù)解題

c++
小樊
110
2024-07-17 15:58:50

在C++中,可以使用 atan2 函數(shù)來(lái)計(jì)算兩個(gè)參數(shù)的反正切值。 atan2 函數(shù)接受兩個(gè)參數(shù),表示 y 坐標(biāo)和 x 坐標(biāo),返回這兩個(gè)坐標(biāo)的反正切值。

例如,可以使用 atan2 函數(shù)來(lái)計(jì)算向量的方向角度。假設(shè)有一個(gè)二維向量 (x, y),可以使用 atan2(y, x) 來(lái)計(jì)算該向量與 x 軸正方向的夾角。

下面是一個(gè)簡(jiǎn)單的示例代碼,展示如何在C++中利用 atan2 函數(shù)來(lái)計(jì)算兩個(gè)點(diǎn)之間的角度:

#include <iostream>
#include <cmath>

int main() {
    double x1, y1, x2, y2;
    std::cout << "Enter the coordinates of point 1 (x1 y1): ";
    std::cin >> x1 >> y1;
    
    std::cout << "Enter the coordinates of point 2 (x2 y2): ";
    std::cin >> x2 >> y2;
    
    double angle = atan2(y2 - y1, x2 - x1) * 180 / M_PI; // Convert radians to degrees
    if (angle < 0) {
        angle += 360; // Normalize angle to be between 0 and 360 degrees
    }
    
    std::cout << "The angle between the two points is: " << angle << " degrees" << std::endl;
    
    return 0;
}

在這個(gè)示例中,用戶(hù)輸入了兩個(gè)點(diǎn)的坐標(biāo) (x1, y1) 和 (x2, y2),然后計(jì)算了這兩個(gè)點(diǎn)之間的角度,并將結(jié)果輸出。

0