![](/img/trans.png)
[英]Is this the correct method of using dot product to find the angle between two vectors? C++ SFML
[英]C++ Angle between two vectors with acos
我正在嘗試使此代碼正常工作,並且給出了角度,但角度不正確,它們的角度不相加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;
}
您不是在比較直角,而是嘗試一下(從具有的點創建矢量):
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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.