简体   繁体   English

ACOS两个向量之间的C ++角度

[英]C++ Angle between two vectors with acos

I'm trying to get this code to work and it gives out angles but not the right ones though, they don't add up to 180° and I can't find the problem. 我正在尝试使此代码正常工作,并且给出了角度,但角度不正确,它们的角度不相加180°,我找不到问题。 I've implemented a Vector2 struct which resembles a two-dimensional Vector and I have been trying to define the ^ operator for it as the function to give the angles between the two vectors. 我已经实现了类似于二维Vector的Vector2结构,并且我一直在尝试为它定义^运算符,以给出两个矢量之间的夹角。

Thanks for the help in advance! 我在这里先向您的帮助表示感谢!

#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace std;

struct Vector2 {
    double x, y;
};

ostream& operator<<(ostream& out, const Vector2& w){
    cout  << '[' << w.x << " , " << w.y << ']';
    return out;
}

double operator*(const Vector2& a, const Vector2& b){
    double w = a.x*b.x + a.y*b.y;
    return w;
}

double absc(const Vector2& d) {
    return sqrt(d*d);  
}

constexpr Vector2 operator+(const Vector2& a, const Vector2& b){
    Vector2 y{a.x+b.x, a.y+a.y};
    return y;
}

constexpr Vector2 operator-(const Vector2& a,const Vector2& b){
    Vector2 z{a.x-b.x, a.y-b.y};
    return z;
}

double operator^(const Vector2& a,const Vector2& b){
    double n = (absc(a))*(absc(b));
    double c = acos((a*b)/n);
    return c;
}

int main(){
    Vector2 a = {1.0, 1.0};
    Vector2 b = {4.0, 7.0};
    Vector2 c = {-2.0, 5.0};
    double d =c^b;
    double e = a^c;
    double f = a^b;
    auto grad = [](double rad) { return rad * (45./atan(1.0)); };

    cout<<"Angle Alpha: "<<grad(c^b)<<"rad "<<d<<"\n";
    cout<<"Angle Beta: "<<grad(a^c)<<"rad "<<e<<"\n";
    cout<<"Angle Gamma: "<<grad(a^b)<<"rad "<<f<<"\n";

    return EXIT_SUCCESS;
}

You are not comparing the right angles, try this instead (create the vectors from the points you have): 您不是在比较直角,而是尝试一下(从具有的点创建矢量):

double d = (a-c)^(a-b);
double e = (b-a)^(b-c);
double f = (c-b)^(c-a);
auto grad = [](double rad) { return rad * (45./atan(1.0)); };

cout<<"Angle Alpha: "<<grad((a-c)^(a-b))<<"rad "<<d;
cout<<"\nAngle Beta: "<<grad((b-a)^(b-c))<<"rad "<<e;
cout<<"\nAngle Gamma: "<<grad((c-a)^(c-b))<<"rad "<<f;

And now you have 180° or pi. 现在您有180°或pi。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM