如何将两点(x1,y1)与(x2,y2)的距离赋值给变量point_dist
平面两点距离计算正确Python实现
原错误代码问题说明
原参考代码存在多处语法和逻辑错误:
- 未导入
math模块就调用math.sqrt方法,会触发名称错误 - 括号不匹配,存在无效的硬编码数值3.0
- 完全不符合距离计算公式,没有对坐标差做平方运算,也没有对两个平方结果求和再开平方
正确实现代码
完整可运行版本(支持读取输入)
import math # 读取空格分隔的四个坐标浮点数 x1, y1, x2, y2 = map(float, input().split()) # 按欧氏距离公式计算 point_dist = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) # 格式化输出结果 print(f"Points distance: {point_dist}")
固定参数测试版本
如果直接用示例输入测试,可简化为:
import math x1, y1, x2, y2 = 1.0, 2.0, 1.0, 5.0 point_dist = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) print(f"Points distance: {point_dist}")
输入1.0 2.0 1.0 5.0时,运行后输出为Points distance: 3.0,符合要求。
内容的提问来源于stack exchange,提问作者Sasha77
相关产品推荐
相关产品推荐

