【问题标题】:Why does my Python program return "ValueError: math domain error"?为什么我的 Python 程序返回“ValueError:数学域错误”?
【发布时间】:2020-06-22 15:09:57
【问题描述】:

我正在制作这个非常简单的程序,它计算玩家坐标和另一个地方坐标之间的距离(对于 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”。有人可以帮我确定问题和可能的解决方案吗?

【问题讨论】:

  • ^ 是异或。使用math.pow** 获取电源。

标签: python math valueerror square-root pythagorean


【解决方案1】:

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

^ symbol 用于按位计算XOR operation。要获取权力,您应该使用math.pow()**,即,

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

或者,您也可以使用math.hypot()

dist = math.hypot(px-x, pz-z)

【讨论】:

  • 非常感谢GoodDeeds!我很感激。我已经好几个月没有做过任何 Python 编程了,而且我犯了这些愚蠢的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 2020-05-06
  • 2019-10-12
  • 1970-01-01
  • 2019-04-03
相关资源
最近更新 更多