設點為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 }