Home  >  Article  >  Backend Development  >  C program to calculate distance between two points

C program to calculate distance between two points

王林
王林forward
2023-09-09 18:41:151193browse

C program to calculate distance between two points

Given the coordinates of two points, the task is to find the distance between the two points and display the result.

There are two points in the two-dimensional plane, assuming A and B have their respective coordinates as (x1, y1) and (x2, y2) and calculate the distance between them, there is a direct formula as follows As shown

$$\sqrt{\lgroup x2-x1\rgroup^{2 } \lgroup y2-y1\rgroup^{2}}$$

The following is the representation Graph of two points and their differences

$$ \frac{(x_2-x_1)}{(x_1,y_1)\:\:\:\:\:\:(y_2-y_1) \:\:\:\:\:\:(x_2,y_2)} $$

The method used below is as follows -

  • The input coordinates are x1, x2, y1 and y2
  • Apply formula to calculate the difference between two points
  • Print distance

Algorithm

Start
Step 1-> declare function to calculate distance between two point
   void three_dis(float x1, float y1, float x2, float y2)
      set float dis = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) * 1.0)
      print dis
step 2-> In main()
   Set float x1 = 4
   Set float y1 = 9
   Set float x2 = 5
   Set float y2 = 10
   Call two_dis(x1, y1, x2, y2)
Stop

Example

#include <stdio.h>
#include<math.h>
//function to find distance bewteen 2 points
void two_dis(float x1, float y1, float x2, float y2) {
   float dis = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2) * 1.0);
   printf("Distance between 2 points are : %f", dis);
   return;
}
int main() {
   float x1 = 4;
   float y1 = 9;
   float x2 = 5;
   float y2 = 10;
   two_dis(x1, y1, x2, y2);
   return 0;
}

Output

If we run the above code it will generate the following output

Distance between 2 points are : 1.414214

The above is the detailed content of C program to calculate distance between two points. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete