Home > Backend Development > C++ > body text

C program to calculate distance between three points in 3D space

PHPz
Release: 2023-08-29 12:41:04
forward
887 people have browsed it

Given a three-dimensional plane and therefore three coordinates, the task is to find the distance between the given points and display the result.

On the three-dimensional plane, there are three coordinate axes. The coordinates of the x-axis are (x1, y1, z1), the coordinates of the y-axis are (x2, y2, z2), and the coordinates of the z-axis are (x3, y3,z). There is a direct formula for calculating the distance between them as follows

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

The following is a diagram showing three different axes and their coordinates

C program to calculate distance between three points in 3D space

The method used below is as follows

  • Input coordinates (x1, y1, z1), (x2, y2, z2) and (x3, y3, z3)
  • Apply the formula to calculate the difference between these points
  • Print distance

Algorithm

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

Example

's translation is:

Example

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

Output

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

Distance between 3 points are : 12.083046
Copy after login

The above is the detailed content of C program to calculate distance between three points in 3D space. 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