[Solved] Distance between 2 points with Java, C++, Python

Write a program to find the distance between 2 points using functions.

Input Format:

Input consists of 4 integers. The first and second integer corresponds to the x-coordinate and y-coordinate of the first point. The third and fourth integer corresponds to the x-coordinate and y-coordinate of the second point.

Output Format:

Output consists of a single floating point number (correct to 2 decimal places.) Refer sample output for formatting details.

Sample Input:

3

6

4

3

Sample Output:

Distance between the 2 points is 3.16

Solution

import java.util.*;
import java.text.DecimalFormat;
import static java.lang.Math.*;
import static java.lang.Math.sqrt;
public class Main {
    public static void main(String[] args) {
        DecimalFormat format = new DecimalFormat("0.00");
        int a, b, c, d;
        Scanner s = new Scanner(System.in);
        a = s.nextInt();
        b = s.nextInt();
        c = s.nextInt();
        d = s.nextInt();
        float dis = findDistance(a, b, c, d);
        //sauravhathi
        System.out.println("Distance between the 2 points is " + format.format(dis));
    }
    public static float findDistance(int p, int q, int r, int s) {
        float temp;
        temp = (float) sqrt(pow(r - p, 2) + pow(s - q, 2));
        return temp;
    }
}

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int a,b,c,d;
    cin >> a >> b >> c >> d;
    //sauravhathi
    printf("Distance between the 2 points is %.2f\n", sqrt(pow(c-a,2)+pow(d-b,2)));
    return 0;
}
a = int(input())
b = int(input())
c = int(input())
print("Distance between the 2 points is %.2f\n", sqrt(pow(c-a,2)+pow(d-b,2)));

Happy Learning – If you require any further information, feel free to contact me.

Share your love
Saurav Hathi

Saurav Hathi

I'm currently studying Bachelor of Computer Science at Lovely Professional University in Punjab.

πŸ“Œ Nodejs and Android 😎
πŸ“Œ Java

Articles: 444

Leave a Reply

Your email address will not be published. Required fields are marked *