You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将两点(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 10:24:03