以下两个语句有什么不同之处?
语句1:
var=2**2*3
语句 2:
var2=2*2*3
我看不出有什么区别。 这引发了以下问题。
如果我们可以使用语句2,为什么要使用语句1?
尝试:
2**3*2
及
2*3*2
< p > **
是“乘方”的运算符。在您的特定操作中,2的平方与2乘以2产生的结果相同。 mmap()
和**
。本以为它们的语义类似于//
,但我错得离谱。我从未见过计算机对我如此生气。 - Qix - MONICA WAS MISTREATED双星号 (**
) 代表乘方。因此,“2乘以2”和“2的二次幂”是相同的,更换数字后你会看到不同。
^
字符的可用性。 - dan04 2**2 means 2 squared (2^2)
2*2 mean 2 times 2 (2x2)
在这种情况下,它们恰好有相同的值,但是... 3**3*4 != 3*3*4
To specifically answer your question Why is the code1 used if we can use code2? I might suggest that the programmer was thinking in a mathematically broader sense. Specifically, perhaps the broader equation is a power equation, and the fact that both first numbers are "2" is more coincidence than mathematical reality. I'd want to make sure that the broader context of the code supports it being
var = x * x * y
in all cases, rather than in this specific case alone. This could get you in big trouble if x is anything but 2.
2**2 = 2的平方
2*2 = 2乘以2
在Python中,**
运算符实际上是“幂运算”,即 2**3 = 8
。
幂运算比乘法优先级更高,因此:
2**2*3 = (2^2)*3
2*2*3 = 2*2*3
顶部的一个符号是“幂”运算符,在这种情况下它相当于2 * 2等于2的2次方。如果你在中间位置放入一个3,你会发现有所不同。