溫馨提示×

如何在C++中利用atan2函數解題

c++
小樊
176
2024-07-17 15:58:50
欄目: 編程語言

在C++中,可以使用 atan2 函數來計算兩個參數的反正切值。 atan2 函數接受兩個參數,表示 y 坐標和 x 坐標,返回這兩個坐標的反正切值。

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

下面是一個簡單的示例代碼,展示如何在C++中利用 atan2 函數來計算兩個點之間的角度:

#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;
}

在這個示例中,用戶輸入了兩個點的坐標 (x1, y1) 和 (x2, y2),然后計算了這兩個點之間的角度,并將結果輸出。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女