叉积基础知识
连接: http://pan.baidu.com/s/1bozE1NT 密码: i7aiios
运行截图spa
//点到直线和线段的最短距离 //求直线间夹角度数 #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; }