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

如何为point_dist赋值两点(x1,y1)与(x2,y2)之间的距离?

两点距离计算与变量point_dist赋值方案

1. 纠正距离计算公式

你给出的公式描述有误,两点(x₁,y₁)与(x₂,y₂)之间的欧几里得距离(平面内两点直线距离)正确公式是:

Distance = √[(x₂ - x₁)² + (y₂ - y₁)²]

对应测试输入1.0 2.0 1.0 5.0,代入计算:

  • x₂-x₁ = 1.0 - 1.0 = 0.0,平方后为0.0
  • y₂-y₁ = 5.0 - 2.0 = 3.0,平方后为9.0
  • 平方和为0.0+9.0=9.0,开根号后得到3.0,和测试结果完全匹配。

2. 代码实现示例(主流语言)

Python

# 绑定测试输入值
x1, y1, x2, y2 = 1.0, 2.0, 1.0, 5.0
# 计算距离并赋值给point_dist
# 方法1:用指数运算实现开根号
point_dist = ((x2 - x1)**2 + (y2 - y1)**2)**0.5
# 方法2:用math模块的sqrt函数更直观
import math
point_dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

Java

public class DistanceCalculation {
    public static void main(String[] args) {
        double x1 = 1.0, y1 = 2.0, x2 = 1.0, y2 = 5.0;
        double point_dist = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
    }
}

C++

#include <cmath>
#include <iostream>

int main() {
    double x1 = 1.0, y1 = 2.0, x2 = 1.0, y2 = 5.0;
    double point_dist = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
    return 0;
}

3. 核心注意点

  • 必须对两个坐标差分别平方后求和,再开根号——这是平面两点直线距离的核心逻辑,也是测试用例得到3.0的关键。
  • 原描述的sqrt(x2 - x1) 和 (y2 - y1)是错误写法,既不符合距离定义,也无法得到正确结果。

内容的提问来源于stack exchange,提问作者summer.benner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 19:10:40