Question #48908

Write a C++ program that takes the (x, y) coordinates of two points and outputs the distance between them using constructors.

Expert's answer

#include <iostream>

#include <cmath>

#include <cstdlib>

using namespace std;

class Point

{

public:

Point(): x(0), y(0) {}

Point(double i_x, double i_y): x(i_x), y(i_y) {}

double getx() {return x;}

double gety() {return y;}

private:

double x;

double y;

};

class Distance

{

public:

Distance(const Point& i_p1, const Point& i_p2): p1(i_p1), p2(i_p2) {}

double getvalue()

{

double dx = p1.getx() - p2.getx();

double dy = p1.gety() - p2.gety();

return sqrt(dx * dx + dy * dy);

}

private:

Point p1;

Point p2;

};

int main(){

double x, y;

cout << "Enter coordinates of the first point, separated by space: ";

cin >> x >> y;

Point p1(x, y);

cout << "Enter coordinates of the second point, separated by space: ";

cin >> x >> y;

Point p2(x, y);

Distance d(p1, p2);

cout << "Distance between these two points is: " << d.getvalue() << endl;

system("pause");

return 0;

}

#include <cmath>

#include <cstdlib>

using namespace std;

class Point

{

public:

Point(): x(0), y(0) {}

Point(double i_x, double i_y): x(i_x), y(i_y) {}

double getx() {return x;}

double gety() {return y;}

private:

double x;

double y;

};

class Distance

{

public:

Distance(const Point& i_p1, const Point& i_p2): p1(i_p1), p2(i_p2) {}

double getvalue()

{

double dx = p1.getx() - p2.getx();

double dy = p1.gety() - p2.gety();

return sqrt(dx * dx + dy * dy);

}

private:

Point p1;

Point p2;

};

int main(){

double x, y;

cout << "Enter coordinates of the first point, separated by space: ";

cin >> x >> y;

Point p1(x, y);

cout << "Enter coordinates of the second point, separated by space: ";

cin >> x >> y;

Point p2(x, y);

Distance d(p1, p2);

cout << "Distance between these two points is: " << d.getvalue() << endl;

system("pause");

return 0;

}

``

## Comments

Assignment Expert18.11.14, 16:46Dear Keerthana,

You're welcome. We are glad to be helpful.

If you liked our service please press like-button beside answer field. Thank

you!

Keerthana17.11.14, 18:06Thank you expert

## Leave a comment