Giải thuật:
Nhập liệu:
1.Nhập tọa độ (x1, y1) của điểm A và tọa độ (x2, y2) của điểm B từ người dùng.
Tính khoảng cách:
Sử dụng công thức tính khoảng cách giữa hai điểm trong mặt phẳng Descartes:
Khoảng cách = √((x2 - x1)^2 + (y2 - y1)^2)
Công thức này dựa trên định lý Pytago: trong tam giác vuông, bình phương cạnh huyền bằng tổng bình phương hai cạnh góc vuông.
Làm tròn kết quả:
Sử dụng hàm setprecision trong C++ để làm tròn kết quả đến 2 chữ số thập phân.
Xuất kết quả:
In ra màn hình khoảng cách đã tính được.
Độ phức tạp:
Độ phức tạp của thuật toán này là O(1)
Code c++ như sau:
#∈clude<bitsstdc++.h>#def∈efifirst#def∈esesecond#def∈elllonglongconst∫N=1e6+3;usingnamespacestd;∫x1,y1,x2,y2;∫ma∈(){c∈⟩x1⟩y1⟩x2⟩y2;cout⟨fixed⟨set≺ision(2)⟨√(x2−x1)⋅(x2−x1)+(y2−y1)⋅(y2−y1);}
# DISTANCE
---
## How to solve this problem?To calculate the distance between two points in a coordinate plane, use the distance formula:d=√(x2−x1)2+(y2−y1)2Where:
- (x1,y1) is the coordinates of the first point.
- (x2,y2) is the coordinates of the second point.
- d is the Euclidean distance between two points.
---
## Full Code
### C++cpp#∈clude<iostream>#∈clude<cmath>/For√andpow()#∈clude<iomanip>/Forset≺ision()usingnamespacestd;∫ma∈(){ios::syncwithstdio(false);c∈.tie(νllptr);∫x1,y1,x2,y2;c∈⟩x1⟩y1⟩x2⟩y2;doub≤d=√pow((x2−x1),2)+pow((y2−y1),2);cout⟨fixed⟨set≺ision(2)⟨d;return0;}
### Pythonpythonimportmath#For√x1,y1,x2,y2=map(∫,∈put().split())d=math.√(x2−x1)∗2+(y2−y1)∗2pr∫({:.2f}.format(d))