设点为Q,线段为P1P2:
判断点Q在该线段上的依据是:①(Q - P1)* (P2 - P1)= 0;② Q在以P1P2为对角线的矩形内;
需要同时满足这两个条件,①保证了Q点在直线上;②保证了Q不在线段的延长线或反向延长线上。
补充矢量叉积的知识:
设矢量P=(x1,y1),矢量Q=(x2,y1)
P * Q = (x1 * y2) - (x2*y1)
代码为:
1 #include <stdio.h> 2 3 typedef struct point 4 { 5 double x; //x坐标 6 double y; //y坐标 7 8 }point; //定义点 9 10 11 //判断点是否在线上,在返回1,不在返回0 12 int onSegement(point p1,point p2,point Q) 13 { 14 double maxx,minx,maxy,miny; 15 16 maxx = p1.x >p2.x ?p1.x :p2.x ; //矩形的右边长 17 minx = p1.x >p2.x ?p2.x :p1.x ; //矩形的左边长 18 maxy = p1.y >p2.y ?p1.y :p2.y ; //矩形的上边长 19 miny = p1.y >p2.y ?p2.y :p1.y ; //矩形的下边长 20 21 if( ((Q.x -p1.x )*(p2.y -p1.y) == (p2.x -p1.x) *(Q.y -p1.y)) && ( Q.x >= minx && Q.x <= maxx ) && ( Q.y >= miny && Q.y <= maxy)) 22 return 1; 23 else 24 return 0; 25 } 26 void main() 27 { 28 point P1,P2,Q; 29 30 printf("input the start point of the line:"); 31 scanf("%f%f",&P1.x ,&P1.y); 32 printf("\n"); 33 34 printf("input the end point of the line:"); 35 scanf("%f%f",&P2.x ,&P2.y ); 36 printf("\n"); 37 38 printf("input the point :"); 39 scanf("%f%f",&Q.x ,&Q.y ); 40 printf("\n"); 41 42 if( onSegement(P1,P2,Q) ) 43 { 44 printf("point on the line\n"); 45 } 46 else 47 { 48 printf("point not on the line\n"); 49 } 50 51 }