Print
Category: Begin
Hits: 277

Begin20. Find the distance between two points with given coordinates \((x_1, y_1)\) and \((x_2, y_2)\) on the plane. The distance is calculated by formula
\(\sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}.\)

Solution in Python 3:

import random
import math

x1,x2 = random.sample(range(-10, 10), 2)
y1,y2 = random.sample(range(-10, 10), 2)

print("Point 1 (x1, y1): ({0},{1})".format(x1, y1))
print("Point 2 (x2, y2): ({0},{1})".format(x2, y2))

side1 = abs(x1 - x2)
side2 = abs(y1 - y2)
print("Side 1: ", side1)
print("Side 2: ", side2)

d = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
print("Distance: ", d)

Solution in C++:

#include <iostream>
#include <cmath>
using namespace std;
int main(){
int x1,y1,x2,y2;
cout << "Enter the coordinates of the 1st point (x1,y1) through the space: ";
cin >> x1 >> y1;
cout << "Enter the coordinates of the 2nd point (x2,y2) through the space: ";
cin >> x2 >> y2;
cout << "Distance between two points: " << sqrt(pow(x2-x1, 2)+pow(y2-y1, 2)) << "." << endl;
return 0;
}