Prompt the user for two points x1 y1 y1 y2 Write a function
Prompt the user for two points (x1, y1), (y1, y2). Write a function that calculates the distance between the points. For a refresher on how to calculate the distance between two points, click here: http://www.mathwarehouse.com/algebra/distance_formula/index.php
Start with this code:
#include <iostream> // YOUR CODE GOES BELOW HERE
// TO HERE
// DO NOT CHANGE ANYTHING BELOW HERE
int main() {
double x1, y1, x2, y2;
cout << \"Enter x1: \";
cin >> x1;
cout << x1 << endl;
cout << \"Enter y1: \";
cin >> y1;
cout << y1 << endl;
cout << \"Enter x2: \";
cin >> x2; cout << x2 << endl;
cout << \"Enter y2: \";
cin >> y2;
cout << y2 << endl;
cout << \"The distance is \";
cout << distance(x1, y1, x2, y2) << endl;
return 0; }
Sample run #1:
Enter x1: -5
Enter y1: 8
Enter x2: 0
Enter y2: -4
The distance is 13
MORE
Sample run #2:
Enter x1: 12.5
Enter y1: 18.7
Enter x2: -13.9
Enter y2: -29.5
The distance is 54.9563
Solution
Please follow the code and comments for description :
CODE :
#include <iostream> // required header files
#include <cmath>
using namespace std;
double distance(double x1, double y1, double x2, double y2); // function declaration
double distance(double x1, double y1, double x2, double y2) { // function initialisation
double distancex = (x2 - x1) * (x2 - x1); // calculating the x distance
double distancey = (y2 - y1) * (y2 - y1); // calculating the y distance
double distance = sqrt(distancex + distancey); // calculating the distance between the points
return distance; // return the value
}
int main() { // driver method
double x1, y1, x2, y2; // required initialisations
cout << \"Enter x1: \"; // prompt the message
cin >> x1;
cout << x1 << endl;
cout << \"Enter y1: \"; // prompt the message
cin >> y1;
cout << y1 << endl;
cout << \"Enter x2: \"; // prompt the message
cin >> x2;
cout << x2 << endl;
cout << \"Enter y2: \"; // prompt the message
cin >> y2;
cout << y2 << endl;
cout << \"The distance is \"; // prompt the message
cout << distance(x1, y1, x2, y2) << endl; // prompt the result
return 0;
}
OUTPUT :
Run 1 :
Enter x1: -5
-5
Enter y1: 8
8
Enter x2: 0
0
Enter y2: -4
-4
The distance is 13
Run 2 :
Enter x1: 12.5
12.5
Enter y1: 18.7
18.7
Enter x2: -13.9
-13.9
Enter y2: -29.5
-29.5
The distance is 54.9563
Hope this is helpful.


