distance on chessboard C语言代码实现
时间: 2024-05-11 09:13:45 浏览: 61
以下是一个用C语言实现棋盘上两个点之间距离的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int x1, y1, x2, y2;
float distance;
printf("Enter the coordinates of first point (x1 y1): ");
scanf("%d %d", &x1, &y1);
printf("Enter the coordinates of second point (x2 y2): ");
scanf("%d %d", &x2, &y2);
distance = sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
printf("The distance between the points (%d,%d) and (%d,%d) is: %f\n", x1, y1, x2, y2, distance);
return 0;
}
```
该程序首先提示用户输入两个点的坐标,然后使用sqrt和pow函数计算两点之间的距离,并将结果打印到屏幕上。
相关问题
distance on chessboard 代码实现
这里提供一个 Python 代码实现,通过输入两个棋盘上的位置,计算它们之间的最短距离。
```
def distance_on_chessboard(pos1, pos2):
"""
计算在棋盘上从 pos1 到 pos2 的最短距离
pos1 和 pos2 是形如 "a1" 或 "h8" 的字符串
"""
# 将位置字符串转换为坐标
x1, y1 = ord(pos1[0]) - 97, int(pos1[1]) - 1
x2, y2 = ord(pos2[0]) - 97, int(pos2[1]) - 1
# 计算横向和纵向的距离
dx, dy = abs(x2 - x1), abs(y2 - y1)
# 返回最短距离
return max(dx, dy)
# 测试代码
print(distance_on_chessboard("a1", "h8")) # 7
print(distance_on_chessboard("d5", "e6")) # 1
print(distance_on_chessboard("h1", "a8")) # 7
```
distance on chessboard
The distance on a chessboard refers to the number of squares between two pieces or locations on the board. It is calculated by counting the number of squares a piece must move horizontally, vertically or diagonally to reach its destination. The maximum distance on a chessboard is 14 squares, which is the distance between the two opposite corners.
阅读全文