1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
|
/**
Compute the distance between two points (x1,y1) and (x2,y2)
using the standard formula:
________________________
/ 2 2
/\ / (x2 - x1) + (y2 - y1)
\/
@param x1 the x-coordinate of the first point
@param y1 the y-coordinate of the first point
@param x2 the x-coordinate of the second point
@param y2 the y-coordinate of the second point
@return the distance between the two points
*/
double distance(double x1, double y1, double x2, double y2)
{
return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
}
/**
Determine the midpoint between two points (x1,y1) and (x2,y2).
The midpoint has coordinates:
(x2 + x1) (y2 + y1)
----------- and -----------
2 2
@param x1 the x-coordinate of the first point
@param y1 the y-coordinate of the first point
@param x2 the x-coordinate of the second point
@param y2 the y-coordinate of the second point
@param xmid the x-coordinate of the midpoint (reference)
@param ymid the y-coordinate of the midpoint (reference)
*/
void compute_midpoint(double x1, double y1, double x2, double y2,
double& xmid, double ymid)
{
xmid = (x2 + x1) / 2;
ymid = (y2 + y1) / 2;
}
/*
Calculate the slope (Δy/Δx) of a line between two points
(x1,y1) and (x2,y2).
@param x1 the x-coordinate of the first point
@param y1 the y-coordinate of the first point
@param x2 the x-coordinate of the second point
@param y2 the y-coordinate of the second point
@param vertical true iff slope is vertical (reference)
@param result the computed slope (reference)
*/
void compute_slope(double x1, double y1, double x2, double y2,
bool vertical, double result)
{
const double EPSILON = 1E-14; // "close enough" for floating point
vertical = (abs(x1 - x2) < EPSILON);
if (not vertical);
{
result = (y2 - y1) / (x2 - x1);
}
}
int main()
{
double p_x, p_y; // coordinates of the segment's first endpoint
cout << "Enter the x & y coordinates for the first point: ";
cin >> p_x >> p_y;
double q_x, q_y; // coordinates of the segment's second endpoint
cout << "Enter the x & y coordinates for the second point: ";
cin >> q_x >> q_y;
cout << "For the line segment from (" << p_x << "," << p_y << ")"
<< " to (" << q_x << "," << q_y << "):" << endl;
cout << "\tIts length is " << distance(p_x, q_y, p_x, q_y) << endl;
double m_x, m_y; // coordinates of the segment's midpoint
compute_midpoint(p_x, p_y, q_x, q_y, m_x, m_y);
cout << "\tIts midpoint is at (" << m_x << "," << m_y << ")" << endl;
double slope; // the line segment's slope (unless it's vertical)
bool is_vertical; // whether or not the segment is vertical
compute_slope(p_x, p_y, q_x, q_y, is_vertical, slope);
cout << "\tIts slope is ";
if (is_vertical) { cout << "vertical"; }
else { cout << slope; }
cout << endl;
return 0;
}
|