我正在尝试使此代码正常工作,并且给出了角度,但是角度不正确,它们的角度不相加180°,我找不到问题。我已经实现了类似于二维Vector的Vector2结构,并且我一直在尝试为其定义^运算符,以给出两个矢量之间的角度。
谢谢您的帮助!
#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;
}
答案 0 :(得分:1)
您不是在比较直角,而是尝试一下(从具有的点创建矢量):
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;
现在您有180°或pi。