Distance between two points
C program to calculate the distance between the two points.
Program
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float x1, y1, x2, y2, dist;
printf("Enter the value of x1\t: ");
scanf("%f", &x1);
printf("Enter the value of y1\t: ");
scanf("%f", &y1);
printf("Enter the value of x2\t: ");
scanf("%f", &x2);
printf("Enter the value of y2\t: ");
scanf("%f", &y2);
dist = sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
printf("\nDistance between the points (%.3f,%.3f) & (%.3f,%.3f) is: %.3f", x1, y1, x2, y2, dist);
getch();
getch();
}
Output
Enter the value of x1 : 5
Enter the value of y1 : 4
Enter the value of x2 : 3
Enter the value of y2 : 2
Distance between the points (5.000,4.000) & (3.000,2.000) is: 2.828
Explanation
In two dimensional plane, each point has two coordinates. Let the two points be A and B with their respective coordinates as (x1, y1) and (x2, y2). To calculate the distance between them there is a direct formula which is as follows:
To find the square root of a number, we use a predefined function sqrt() which is defined in math.h library header file.
Note that, %.3f is used in the printf statement. Let us understand what this means.
By default, a float value is printed upto 6 decimal places.
For example,
output:
34.450000
we can customize the above output by telling how many digits are required after decimal. This can be done by modifying the format specifier. Instead of %f, %.nf is used, where n is the number of digits after decimal
In this, output will be displayed upto 3 decimal places.
output:
34.450
In this, output will be displayed upto 4 decimal places.
output:
34.4500
To find the square root of a number, we use a predefined function sqrt() which is defined in math.h library header file.
Note that, %.3f is used in the printf statement. Let us understand what this means.
By default, a float value is printed upto 6 decimal places.
For example,
float dist = 34.45;
printf("%f",dist);
output:
34.450000
we can customize the above output by telling how many digits are required after decimal. This can be done by modifying the format specifier. Instead of %f, %.nf is used, where n is the number of digits after decimal
printf("%.3f",dist);
In this, output will be displayed upto 3 decimal places.
output:
34.450
printf("%.4f",dist)
In this, output will be displayed upto 4 decimal places.
output:
34.4500