【发布时间】:2021-06-24 09:40:25
【问题描述】:
这是我的功能。
def is_square(n):
x = n ** 0.5
return((x >= 0) & (x % 1 == 0))
当我跑步时
is_square(-1)
我收到此错误消息:
Traceback (most recent call last):
File "<ipython-input-183-33fbc4575bf6>", line 1, in <module>
is_square(-1)
File "<ipython-input-182-32cb3317a5d3>", line 3, in is_square
return((x >= 0) & (x % 1 == 0))
TypeError: '>=' not supported between instances of 'complex' and 'int'
但是,此功能的各个组件都可以完美运行。
x = -1 ** 0.5
x >= 0
Out[185]: False
x % 1 == 0
Out[186]: True
(x >= 0) & (x % 1 == 0)
Out[189]: False
为什么我的功能不起作用?
【问题讨论】:
-
这不等同。在你的程序中是
(-1) ** 0.5,而不是-1 ** 0.5。(-1)**0.5是一个复数,支持与实数不同的运算。 -
对
-1求平方根,你认为应该是什么结果?当您将其与 0 进行比较时,您期望会发生什么?错误信息写在not supported between instances of 'complex' and 'int'的地方,你真的明白'complex'在这里是什么意思吗?看起来你实际上可能有一个数学理论问题,而不是一个编程问题。 -
明白 - 谢谢!
标签: python function integer boolean complex-numbers