📜  程序计算两点之间的距离

📅  最后修改于: 2021-05-06 03:28:29             🧑  作者: Mango

给出了二维图形的两个坐标(x1,y1)和(x2,y2)。找到它们之间的距离。
例子:

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

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

我们将使用从勾股定理得出的距离公式。两点(x1,y1)和(x2,y2)之间的距离的公式为
距离= $\sqrt{(x2-x1)^{2} + (y2-y1)^{2}}$
我们可以通过简单地应用毕达哥拉斯定理来获得上述公式

以下是上述想法的实现。

C++
#include 
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


Javascript


输出:

1.41421