Calculate the angle between two straight lines (C++)

Computing the acute angle of two lines can be done using knowledge of vectors. In C++, we can define a function to calculate the angle between two vectors, and judge the size of the angle according to the cosine value of the angle. Here is a sample code written in C++:

#include <iostream>
#include <cmath>

using namespace std;

struct Vector {
    
    
    double x;
    double y;
};

// 计算向量的长度
double vectorLength(const Vector& v) {
    
    
    return sqrt(v.x * v.x + v.y * v.y);
}

// 计算两个向量的点积
double dotProduct(const Vector& v1, const Vector& v2) {
    
    
    return v1.x * v2.x + v1.y * v2.y;
}

// 计算两个向量的夹角(以弧度为单位)
double angleBetweenVectors(const Vector& v1, const Vector& v2) {
    
    
    double cosTheta = dotProduct(v1, v2) / (vectorLength(v1) * vectorLength(v2));
    return acos(cosTheta);
}

int main() {
    
    
    Vector line1, line2;

    cout << "请输入第一条直线的向量(x, y): ";
    cin >> line1.x >> line1.y;

    cout << "请输入第二条直线的向量(x, y): ";
    cin >> line2.x >> line2.y;

    double angle = angleBetweenVectors(line1, line2);

    // 将弧度转换为角度
    double degrees = angle * 180.0 / M_PI;

    cout << "两条直线的锐角为: " << degrees << "度" << endl;

    return 0;
}

Note that this sample code assumes that the lines represented by both vectors start at the origin (0, 0). If the starting point of the line is not at the origin, we need to translate it to the origin before calculating. Also, division by zero and other exceptions should be handled. The sample code here is just to demonstrate how to calculate the acute angle of two straight lines.

Guess you like

Origin blog.csdn.net/weixin_42990464/article/details/132079696