Examples C++

Calculate the Distance Between Two Points in the Plane

In this C++ example, we demonstrate how to calculate the distance bewteen two points in the plane. The code contains a simple function, which calculates the distance using the distance formula. In the main function, calculate the distance for two pairs of points.

Code:

#include <iostream>
#include <cmath>

double Distance(double dX0, double dY0, double dX1, double dY1)
{
    return sqrt((dX1 - dX0)*(dX1 - dX0) + (dY1 - dY0)*(dY1 - dY0));
}

int main()
{
    using namespace std;

    // Calculate two distances
    cout << "Distance = " << Distance(0.0, 0.0, 0.0, 1.0) << endl;
    cout << "Distance = " << Distance(2.0, 4.0, 3.0, 1.0) << endl;

    return 0;
}

Output:

Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.