Giới thiệu
Cho tọa độ hai điểm A(x1, y1) và B(x2, y2) trong mặt phẳng 2D. Tính khoảng cách giữa chúng.
Công thức khoảng cách Euclid:
d = √((x2-x1)² + (y2-y1)²)
Ví dụ
Input: x1=4, y1=9, x2=5, y2=10 → Output: 1.414214
Thuật toán
Hàm two_dis(x1, y1, x2, y2): dis = sqrt(pow(x2-x1, 2) + pow(y2-y1, 2)) In dis Hàm main: x1=4, y1=9, x2=5, y2=10 Gọi two_dis
Code C
#include <stdio.h>
#include <math.h>
void two_dis(float x1, float y1, float x2, float y2) {
float dis = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
printf("Distance between 2 points are : %f", dis);
}
int main() {
float x1 = 4, y1 = 9, x2 = 5, y2 = 10;
two_dis(x1, y1, x2, y2);
return 0;
}
Kết quả
Distance between 2 points are : 1.414214
Lưu ý
Cần include <math.h> và compile với flag -lm (link thư viện math).