微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

矢量到角度转换函数有时返回弧度,有时返回度数

如何解决矢量到角度转换函数有时返回弧度,有时返回度数

我尝试编写一个程序,其中计算一个向量,该向量平分共享一个公共点的两条线之间的角度。

为此,我想出了一些代码(因为这不是我唯一想做的事情,代码有点长,但我已经将问题归结为这个问题。):

#include <iostream>
#include <cmath>

// A 2D Vector class
class PVector {

public: PVector() = default;
public: PVector(double _x,double _y) : x(_x),y(_y) {};

public: double x,y;

public: PVector set(double _x,double _y) {
        x = _x,y = _y;
        return *this;
    };
    
public: double getMag() const {
        return sqrt(x * x + y * y);
    };

public: PVector setMag(double mag) {
        mag *= getMag();
        return (mag == 0) ? set(0,0) : set(x / mag,y / mag);
    };

public: PVector &operator+=(const PVector &rhs) {
        x += rhs.x,y += rhs.y;
        return *this;
    };

public: PVector operator+(const PVector &rhs) {
        return PVector(*this) += rhs;
    };

public: PVector &operator-=(const PVector &rhs) {
        x -= rhs.x,y -= rhs.y;
        return *this;
    };

public: PVector operator-(const PVector &rhs) {
        return PVector(*this) -= rhs;
    };
public: PVector &operator*=(const double &m) {
        x *= m,y *= m;
        return *this;
    };
};

// A function to convert a 2D vector into an angle
double vector2Angle(double x,double y) {

    if (x == 0)
        return (y >= 0) ? 0 : 180;
    else if (y == 0)
        return (x > 0) ? 90 : 270;

    double angle = atan(y / x);

    // bottom left (90 - 180)
    if (x < 0 && y < 0)
        // angle is positive (180 location)
        angle = M_PI / 2;
        // top left (0 - 90)
    else if (x < 0)
        // angle is negative (90 positive) + (0 location)
        angle += M_PI / 2;
        // bottom right (180 - 270)
    else if (y < 0)
        // angle is negative (90 positive) + (180 location)
        angle += 1.5 * M_PI;
        // top right (270 - 360)
    else {
        angle += 1.5 * M_PI;
        // angle is positive
    }
    return angle;
};
double vector2Angle(PVector v) {
    return vector2Angle(v.x,v.y);
};

int main()
{
    PVector p0 = PVector(90,90);
    PVector p1 = PVector(10,90);
    PVector p2 = PVector(10,10);

// The sum of two unit vectors must return a vector that bisects the angle between the two vectors.
    std::cout << "Expected: " << (vector2Angle(p1 - p0) + vector2Angle(p1 - p2)) / 2 << std::endl;
    std::cout << "Got: " << vector2Angle((p1 - p0).setMag(1) + (p1 - p2).setMag(1)) << std::endl;
    return 0;
}

根据直觉,输出应该是 135° 或 315°,但程序提供:

Expected: 135
Got: 0.785398

关于这个输出的第一个奇怪的事情是,尽管 vector2Angle 返回一个弧度值,但它以度为单位。更奇怪的是,两个结果的单位不同。最后我想知道我在计算中的错误是因为 0.785...弧度大约是 45° 而不是 135°。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。