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

C program to calculate distance between two points

王林
Release: 2023-09-09 18:41:15
forward
1288 people have browsed it

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
Copy after login

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;
}
Copy after login

Output

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

Distance between 2 points are : 1.414214
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template