python中的“Power of”

2024-03-29 06:14:17 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么当:

>> b = -1
>> b**2
1

但是:

>> -1**2
-1

如果我导入数学库,没问题。

>> from math import pow
>> pow(b,2)
1.0
>> pow(-1,2)
1.0

Tags: fromimport数学mathpow
3条回答

因为它的工作是1而不是1作为一个整体。这将产生预期的结果。

(-1)**2

它与运算符优先级有关。

试试看

(-1)**2

首先对**求值,然后对-求值。因此,你得到了-1

对于pow函数,首先评估-1

参见https://docs.python.org/2/reference/expressions.html#the-power-operator上的参考

从Python文档中: https://docs.python.org/3/reference/expressions.html#the-power-operator

The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right.

Thus, in an unparenthesized sequence of power and unary operators, the operators are evaluated from right to left (this does not constrain the evaluation order for the operands): -1**2 results in -1.

相关问题 更多 >