Program to calculate distance between two points

1

You are given two co-ordinates (x1, y1) and (x2, y2) of a two dimensional graph. Find the distance between them.

Examples:

Input : x1, y1 = (3, 4)
        x2, y2 = (7, 7)
Output : 5

Input : x1, y1 = (3, 4) 
        x2, y2 = (4, 3)
Output : 1.41421

We will use the distance formula derived from Pythagorean theorem. The formula for distance between two point (x1, y1) and (x2, y2) is

Distance = $\sqrt{(x2-x1)^{2} + (y2-y1)^{2}}$

We can get above formula by simply applying Pythagoras theorem


Image Source : Wikimedia

Below is the implementation of above idea.

C++

#include <bits/stdc++.h>
using namespace std;

// Function to calculate distance
float distance(int x1, int y1, int x2, int y2)
{
    // Calculating distance
    return sqrt(pow(x2 - x1, 2) + 
                pow(y2 - y1, 2) * 1.0);
}

// Drivers Code
int main()
{
    cout << distance(3, 4, 4, 3);
    return 0;
}

Python3

# Python3 program to calculate 
# distance between two points

import math

# Function to calculate distance
def distance(x1 , y1 , x2 , y2):

    # Calculating distance
    return math.sqrt(math.pow(x2 - x1, 2) +
                math.pow(y2 - y1, 2) * 1.0)

# Drivers Code
print("%.6f"%distance(3, 4, 4, 3))

# This code is contributed by "Sharad_Bhardwaj".


Output:

1.41421

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:



1 Average Difficulty : 1/5.0
Based on 2 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.