用 math.hypot 计算两点坐标差的欧几里得距离。
OJ: noi_openjudge
题目 ID: ch0103-16
难度:入门
标签:数学几何python
日期: 2026-07-30 23:01
题意
输入平面两点坐标,输出线段长度,保留 3 位小数。
思路
距离公式是 math.hypot(dx, dy) 直接表达该公式,也比手写平方根更清晰。
代码
Python代码
python
import math
x1, y1 = map(float, input().split())
x2, y2 = map(float, input().split())
print(f"{math.hypot(x1 - x2, y1 - y2):.3f}")C++代码
cpp
#include <cstdio>
#include <cmath>
int main(){
double xa,ya,xb,yb;
scanf("%lf%lf%lf%lf",&xa,&ya,&xb,&yb);
double ans = sqrt((xa-xb)*(xa-xb)+(ya-yb)*(ya-yb));
printf("%0.3lf\n",ans);
return 0;
}复杂度
时间复杂度和额外空间复杂度均为
总结
二维两点距离优先记住 math.hypot,它避免手写平方和开方。