#include <cmath>
using namespace std;
typedef struct
{
double x, y;
}pp;
double absl(pp p)
{
//double r;
return p.x-p.y;
}
pp to_vec(pp p, pp q)
{
pp r;
r.x = q.x-p.x;
r.y = q.y-p.y;
return r;
}
//Compute the dot product AB . BC
/*int dot(int[] A, int[] B, int[] C){
AB = new int[2];
BC = new int[2];
AB[0] = B[0]-A[0];
AB[1] = B[1]-A[1];
BC[0] = C[0]-B[0];
BC[1] = C[1]-B[1];
int dot = AB[0] * BC[0] + AB[1] * BC[1];
return dot;
}*/
double dot(pp p, pp q)
{
double r;
r = p.x*q.x + p.y*q.y;
return r;
}
//Compute the cross product AB X AC
/*int cross(int[] A, int[] B, int[] C){
AB = new int[2];
AC = new int[2];
AB[0] = B[0]-A[0];
AB[1] = B[1]-A[1];
AC[0] = C[0]-A[0];
AC[1] = C[1]-A[1];
int cross = AB[0] * AC[1] - AB[1] * AC[0];
return cross;
}*/
pp crs(pp p, pp q)
{
pp r;
r.x = p.x*q.y;
r.y = p.y*q.x;
//x1*y2 - y1*x2
return r;
}
//Compute the distance from A to B
/*double distance(int[] A, int[] B){
int d1 = A[0] - B[0];
int d2 = A[1] - B[1];
return sqrt(d1*d1+d2*d2);
}*/
double dis(pp p, pp q)
{
double r;
r = sqrt((p.x-q.x)*(p.x-q.x)+(p.y-q.y)*(p.y-q.y));
return r;
}
//Compute the distance from AB to C
//if isSegment is true, AB is a segment, not a line.
/*double linePointDist(int[] A, int[] B, int[] C, boolean isSegment){
double dist = cross(A,B,C) / distance(A,B);
if(isSegment){
int dot1 = dot(A,B,C);
if(dot1 > 0)return distance(B,C);
int dot2 = dot(B,A,C);
if(dot2 > 0)return distance(A,C);
}
return abs(dist);
}*/
double dist(pp p, pp q, pp r, bool isSegment)
{
double s;
s = absl(crs(to_vec(p, q), to_vec(p, r))) / dis(p, q);
if(isSegment)
{
int dot1 = dot(to_vec(p, q), to_vec(p, r));
if(dot1 > 0) return dis(q,r);
int dot2 = dot(to_vec(q, p), to_vec(q, r));
if(dot2 > 0) return dis(p,r);
}
return fabs(s);
}
int main()
{
pp A, B, C;
while(1)
{
printf("Enter 3 points:\n");
scanf("%lf %lf %lf %lf %lf %lf", &A.x, &A.y, &B.x, &B.y, &C.x, &C.y);
pp AB, BC;
AB = to_vec(A, B); //make vector
printf("AB i-> %lf j-> %lf\n", AB.x, AB.y);
BC = to_vec(B, C); //make vector
printf("BC i-> %lf j-> %lf\n", BC.x, BC.y);
double dt;
pp cr;
dt = dot(AB, BC); //AB . BC
printf("AB . BC %lf\n", dt);
cr = crs(AB, BC); //AB X BC
printf("AB X BC i-> %lf j-> %lf\n", cr.x, cr.y);
double d;
d = dis(A, B); //distance from A to B
printf("distance from A to B is %lf\n", d);
bool issegment;
double p_d1, p_d2;
issegment = 0;
p_d1 = dist(A, B, C, issegment); //distance from AB to C (AB is a line)
printf("distance from AB line to C is %lf\n", p_d1);
issegment = 1;
p_d2 = dist(A, B, C, issegment); //distance from AB to C (AB is a segment)
printf("distance from AB segment to C is %lf\n", p_d2);
}
return 0;
}
No comments:
Post a Comment