21xrx.com
2025-04-08 14:39:34 Tuesday
文章检索 我的文章 写文章
曼哈顿距离C++代码示例
2023-07-13 07:31:45 深夜i     22     0
曼哈顿距离 C++ 代码示例

曼哈顿距离是一种计算两个点之间距离的方法,其计算方式是将两点在坐标系中的横纵坐标差值相加。在计算机科学中,曼哈顿距离经常用于寻找最近邻的算法中。

以下是曼哈顿距离的C++代码示例:

#include <iostream>
#include <cmath>
using namespace std;
int main() {
  double x1, y1, x2, y2, manhattan_distance;
 
  // 获取第一个点的坐标
  cout << "Enter the x and y coordinates of the first point: ";
  cin >> x1 >> y1;
  
  // 获取第二个点的坐标
  cout << "Enter the x and y coordinates of the second point: ";
  cin >> x2 >> y2;
 
  // 计算曼哈顿距离
  manhattan_distance = abs(x1 - x2) + abs(y1 - y2);
  
  // 输出结果
  cout << "The Manhattan distance between the two points is: " << manhattan_distance << endl;
  
  return 0;
}

以上代码中,我们通过 `abs()` 函数计算了横坐标和纵坐标的差值的绝对值之和,得到了曼哈顿距离。

在实际使用中,曼哈顿距离常常与其他距离度量方法一起使用,例如欧几里得距离和切比雪夫距离等。

总的来说,曼哈顿距离是一种简单而有效的度量方法,在计算机科学和应用数学等领域具有广泛的应用。

  
  
下一篇: 小数点后n位

评论区

请求出错了