Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Chương trình C tính khoảng cách hai điểm trong không gian 3D

Giới thiệu

Cho tọa độ hai điểm trong không gian 3D: A(x1, y1, z1) và B(x2, y2, z2). Tính khoảng cách giữa chúng.

Công thức khoảng cách Euclid 3D:

d = √((x2-x1)² + (y2-y1)² + (z2-z1)²)

Ví dụ

Input: (4,9,-3) và (5,10,9) → Output: 12.083046

Thuật toán

Hàm three_dis(x1, y1, z1, x2, y2, z2):
  dis = sqrt(pow(x2-x1,2) + pow(y2-y1,2) + pow(z2-z1,2))
  In dis

Hàm main:
  Khởi tạo 6 tọa độ
  Gọi three_dis

Code C

#include <stdio.h>
#include <math.h>

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));
    printf("Distance between 3 points are : %f", dis);
}

int main() {
    float x1 = 4, y1 = 9, z1 = -3;
    float x2 = 5, y2 = 10, z2 = 9;
    three_dis(x1, y1, z1, x2, y2, z2);
    return 0;
}

Kết quả

Distance between 3 points are : 12.083046