Wednesday, September 30, 2009

Sample Code to find distance between a point & a line segment that connects two points in C++

/*This code snippet finds the distance between a P( x,y)

 and a line segement that connects 2 points P1(x1,y1) and P2(x2,y2) */


int main()
 {
 float x1,y1,x2,y2;
 float x,y;
 char ch;
   do
   {
 clrscr();
 cout<<"\n\nEnter x position of the Point:";
 cin>>x;
 cout<<"\nEnter y position of the Point:";
 cin>>y;
 cout<<"\n\nEnter x position of the frist Point:";
 cin>>x1;
 cout<<"\nEnter y position of the frist Point:";
 cin>>y1;
 cout<<"\n\nEnter x position of the second Point:";
 cin>>x2;
 cout<<"\nEnter y position of the second Point:";
 cin>>y2;
 float linedist,dist1,dist2;
 linedist = sqrt( (( x1-x2 )*( x1-x2 ))+(( y1-y2 )*( y1-y2 )) );
 dist1 = sqrt( (( x1-x )*( x1-x ))+(( y1-y )*( y1-y )) );
 dist2 = sqrt( (( x-x2 )*( x-x2 ))+(( y-y2 )*( y-y2 )) );
 float height = linedist*(dist1)/(dist1+dist2);
 
 float distance = sqrt( (dist1*dist1) - (height*height) );
 cout<<"\n\nDistance minimum of point from line is::" << distance << "\n   

 \ncontinue[Y/N]  ??";
 cin>>ch;
   }
   while(ch!='n' && ch!='N');
 return 0;
 }

No comments:

Post a Comment