Программа для расчета расстояния между двумя точками

Опубликовано: 18 Января, 2022

Вам даны две координаты (x1, y1) и (x2, y2) двумерного графа. Найдите расстояние между ними.
Примеры:

 Ввод: x1, y1 = (3, 4)
        х2, у2 = (7, 7)
Выход: 5

Ввод: x1, y1 = (3, 4) 
        х2, у2 = (4, 3)
Выход: 1.41421

Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.

Мы будем использовать формулу расстояния, полученную из теоремы Пифагора. Формула для расстояния между двумя точками (x1, y1) и (x2, y2):
Расстояние =
Мы можем получить формулу выше, просто применив теорему Пифагора

Ниже представлена реализация вышеизложенной идеи.

 

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;
}

Java

// Java code to compute distance
 
class GFG
{
    // Function to calculate distance
static double distance(int x1, int y1, int x2, int y2)
{
    // Calculating distance
    return Math.sqrt(Math.pow(x2 - x1, 2) +
                Math.pow(y2 - y1, 2) * 1.0);
}
    //Driver code
    public static void main (String[] args)
    {
        System.out.println(Math.round(distance(3, 4, 4, 3)*100000.0)/100000.0);
    }
}
 
// This code is contributed by
// Anant Agarwal.

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".

C#

// C# code to compute distance
using System;
 
class GFG
{
    // Function to calculate distance
    static double distance(int x1, int y1, int x2, int y2)
    {
        // Calculating distance
        return Math.Sqrt(Math.Pow(x2 - x1, 2) +
                      Math.Pow(y2 - y1, 2) * 1.0);
    }
     
    // Driver code
    public static void Main ()
    {
        Console.WriteLine(Math.Round(distance(3, 4, 4, 3)
                                   * 100000.0)/100000.0);
    }
}
 
// This code is contributed by
// vt_m.

PHP

<?php
// PHP code to compute distance
 
// Function to calculate distance
function distance($x1, $y1, $x2, $y2)
{
     
    // Calculating distance
    return sqrt(pow($x2 - $x1, 2) +
                pow($y2 - $y1, 2) * 1.0);
}
 
// Driver Code
echo(distance(3, 4, 4, 3));
 
// This code is contributed by Ajit.
?>

Javascript

<script>
 
// Function to calculate distance
function distance(x1, y1, x2,  y2)
{
    // Calculating distance
    return Math.sqrt(Math.pow(x2 - x1, 2) +
                Math.pow(y2 - y1, 2) * 1.0);
}
 
// Drivers Code
document.write(distance(3, 4, 4, 3));
 
// This code is contributed by noob2000.
</script>

Выход:

 1,41421

Вниманию читателя! Не прекращайте учиться сейчас. Получите все важные математические концепции для соревновательного программирования с курсом Essential Maths for CP по доступной для студентов цене. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .