This is a good tutorial working with classes in c++. Our program starts and asks the user to enter the coordinates of two points. The program returns the middle point and the distance between the two points.
#include <iostream> #include <math.h> using namespace std; class Point { private: double x,y; public: Point() { x=y=0;} Point(double a) {x=y=a;} Point(double a, double b) {x=a; y=b;} void Point::display() { cout <<"("<<x<<","<<y<<")"<<endl; } double Point::get_y() {return y;} double Point::get_x() {return x;} }; class Segment { private: Point p1,p2,mid; double xm,ym,len, tmp1, tmp2; public: Segment(Point a) { Point p; p1=p; p2=a;} Segment(Point a, Point b) { p1=a; p2=b;} void Segment::display() { cout <<"The first point is: "; p1.display(); cout <<"The second point is: "; p2.display(); } void Segment::middle() { xm = (p2.get_x() + p1.get_x())/2; ym = (p2.get_y() + p1.get_y())/2; Point mid(xm,ym); cout <<"To middle point is: "; mid.display(); } void Segment::length() { tmp1 = (p2.get_x()-p1.get_x()) * (p2.get_x()-p1.get_x()); //DEBUG cout <<tmp1<<endl; tmp2 = (p2.get_y()-p1.get_y()) * (p2.get_y()-p1.get_y()); //DEBUG cout <<tmp2<<endl; len = sqrt(tmp1 + tmp2); cout <<"The distance between these two points is:"<<len<<endl; } }; int main () { double x1, y1, x2, y2; //Point p1; //p1.display(); //Point p2(3); //p2.display(); //Point p3(-1,8); //p3.display(); //Point p4(3,6); //p4.display(); cout <<"Enter x1:"; cin >> x1; cout <<"Enter y1:"; cin >> y1; cout <<"Enter x2:"; cin >> x2; cout <<"Enter y2:"; cin >> y2; Point p5(x1,y1); Point p6(x2,y2);; Segment s1(p5,p6); s1.display(); s1.middle(); s1.length(); system("PAUSE"); return 0; }
Feed for this Entry Trackback Address The permalink
Be the first to comment this entry.


Recent Comments