【问题标题】:What isnt my python code running? [closed]我的 python 代码没有运行什么? [关闭]
【发布时间】:2017-11-18 13:37:54
【问题描述】:

我的代码给了我一些错误 回溯(最近一次通话最后): 文件“python”,第 7 行,在 ValueError:数学域错误

  import math
  a= 3
  b= 5
  c= 2
  d= b^2 -4*a*c
  x1 = math.sqrt(d)
  print(x1)

【问题讨论】:

  • 我认为b^2 应该是b**2
  • ^ 是按位异或,您想使用** 进行求幂。
  • 所以你知道 - “为什么这段代码不起作用?”是堆栈溢出本身定义的“关闭”投票选项(人们可以投票关闭一个问题,以便除非该问题被编辑以符合站点指南,否则无法回答)。您的标题对可能遇到相同问题的其他人没有帮助。

标签: python math sqrt math.sqrt


【解决方案1】:

d 在没有实解时为负数,因此它的平方也不是实数:
另请注意,b^2 不是 bsquared,而是b xor 2。对于b square,使用b**2,或b*b

import math

a = 3
b = 5
c = 2

d = b**2 - 4*a*c      # Attention, b^2 is not b square, use b**2
if d > 0:
    x1 = math.sqrt(d)
    print(x1)
else:
print("there are no real roots")

【讨论】:

    【解决方案2】:

    您的d-17(您很可能想使用** 而不是^

    What is the root of a negative number?

    That is what the exception is saying

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      相关资源
      最近更新 更多