-1

我正在制作这个非常简单的程序,它计算玩家坐标与另一个地方坐标之间的距离(对于 Minecraft)。

import math
px = int(input("Your x-coordinate: "))
pz = int(input("Your z-coordinate: "))
x = int(input("X-coordinate of destination: "))
z = int(input("z-coordinate of destination: "))
dist = math.sqrt((px-x)^2+(pz-z)^2)
print("Distance is %d meters." % dist)

当我输入 (0, 0) 作为我的坐标和 (1, 1) 作为另一个地方的坐标时,Python 返回“ValueError:数学域错误”而不是根 2 的预期值。虽然当我输入 (0, 0)作为我的坐标和其他地方的坐标,Python 返回“0”。有人可以为我确定问题和可能的解决方案吗?

4

1 回答 1

2

In

dist = math.sqrt((px-x)^2+(pz-z)^2)

The ^ symbol is used for the bitwise XOR operation. For taking power, you should use either math.pow() or **, i.e.,

dist = math.sqrt((px-x)**2+(pz-z)**2)

Alternatively, you can also use math.hypot():

dist = math.hypot(px-x, pz-z)
于 2020-03-10T16:58:54.877 回答