叉積

叉積基礎知識
連接: http://pan.baidu.com/s/1bozE1NT 密碼: i7aiios

clipboard.png

運行截圖spa

clipboard.png

//點到直線和線段的最短距離
//求直線間夾角度數

#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
#define PI 3.1415926

struct _point
{
    double x;
    double y;
};
double distance(_point a , _point b = { 0,0 });
double shortest_dis(_point a, _point b, _point c);
double cross(_point AB, _point AC);
double degree(_point a, _point b, _point c);
bool judge_IsOutOfLine(_point AB, _point BC);

int main()
{
    _point a, b, c;
    cout << "please scanf three points: a、b、c" << endl;
    cin >> a.x >> a.y >> b.x >> b.y >> c.x >> c.y;
    cout <<"the S of triangle made up the three points:    "<< 
        0.5*abs(cross({ b.x - a.x,b.y - a.y }, { c.x - a.x,c.y - a.y }))<<endl;
    cout << "the shortest distance from c to ab:        " << abs(shortest_dis(a, b, c)) << endl;
    cout << "the degree between ab and ac:            " << degree(a, b, c) << endl;
    return 0;
}

//計算a,b點距離
double distance(_point a , _point b)
{
    return sqrt(pow(a.x - b.x, 2) + pow(a.y - b.y, 2));
}

//計算點c 到直線ab 的垂直距離

double shortest_dis(_point a, _point b, _point c)
{
    //|ab|,底
    double ab_dis = distance(a, b);
    double dis = 0;
    _point BC = { c.x - b.x,c.y - b.y };//bc向量
    //ab向量、ac向量
    a = { b.x - a.x,b.y - a.y };
    c = { c.x - a.x,c.y - a.y };
    //×積,便是,以ab,ac線段圍成的 平行四邊形S
    dis = cross(a, c) / ab_dis;
    if (judge_IsOutOfLine(a, BC))//C在AB線段外
    {
        dis = distance(BC);
    }
    return dis;
}

//計算叉積,AB,AC向量
//爲-,AB逆時針到AC,爲+,AB順時針到AC,0,ABC在同一條直線上

double cross(_point AB, _point AC)
{
    return AB.x*AC.y - AC.x*AB.y;
}

//根據×積求向量間夾角

double degree(_point a, _point b, _point c)
{
    //|AB×AC| = |AB|*|AC|*sin(&)
    _point AB = { b.x - a.x,b.y - a.y };
    _point AC = { c.x - a.x,c.y - a.y };
    return asin(abs((cross(AB, AC) / (distance(AB)*distance(AC)))))/(PI / 180);
}

//判斷點是否在線段外——經過AB.BC點積判斷
bool judge_IsOutOfLine(_point AB,_point BC)
{
    double judge = AB.x*BC.x + AB.y*BC.y;
    if (judge >= 0)//銳角-線段外
    {
        return true;
    }
    return false;
}
相關文章
相關標籤/搜索