/* This program uses a class Line and a struct Point to calculate the intersection point between 2 lines. */ #include #include bool equal(double,double); // Tests to see if two double values are equal. struct Point{ // struct has the same syntax as class, public: // except there are no function members of double x_coord, y_coord; // a struct. All the data members of a }; // struct should be public. class Line{ private: double slope, intercept; Point intersect_pt; public: void get_line_data(); void show_line_data(); void calc_intersect_pt(Line); }; void Line :: get_line_data () { cout << "Enter the slope and the y-intercept of the line: "; cin >> slope >> intercept; } void Line :: show_line_data () { cout << "Slope = " << slope << ", Intercept = " << intercept << ".\n"; } void Line :: calc_intersect_pt (Line crossing_line){ /* First handle the special cases where the 2 lines have the same slope. */ if (equal(crossing_line.slope, slope)){ if (equal(intercept, crossing_line.intercept)) cout << "These two lines are identical." << endl; else cout << "These two lines are parallel." << endl; } /* This is the general case, when the 2 lines intersect in a point. */ else{ intersect_pt.x_coord = (crossing_line.intercept - intercept) / (slope - crossing_line.slope); intersect_pt.y_coord = slope * intersect_pt.x_coord + intercept; cout << "The intersection point is (" << intersect_pt.x_coord << "," << intersect_pt.y_coord << ")." << endl; /* Notice that intersect_pt is a data member of the object which calls this function. Then since intersect_pt is of type Point, which is a struct, we access its x coordinate by using intersect_pt.x_coord */ } } void main() { Line line1, line2; line1.get_line_data(); line2.get_line_data(); line1.show_line_data(); line2.show_line_data(); line1.calc_intersect_pt (line2); } bool equal(double x, double y){ double tolerance = 1e-10; return (fabs(x-y)