Python pow() 函数用法
2023-09-17 22:28:45
pow()
方法返回数字的指定指数幂。
pow() 语法:
pow(base, exponent, modulus)
参数:
- base:需要返回其指数幂的基数。
- 指数:作为指数的整数。
- 模数:(可选)模运算的整数(pow(base, exp) % mod)。
返回值:
返回一个整数值。
以下示例计算开机数字。
print('2 x 2 = ', pow(2,2))
print('3 x 3 = ', pow(3,2))
print('3 x 3 x 3 = ', pow(3,3))
print('1/(2 x 2) = ', pow(2,-2))
输出:
2 x 2 = 4
3 x 3 = 9
3 x 3 x 3 = 27
3 x 3 x 3 x 3 = 81
模量参数返回 pow(base, exp) % mod 结果,如下所示。
print('2 x 2 % 2 = ', pow(2,2,2))
print('3 x 3 % 2 = ', pow(3,2,2))
print('3 x 3 x 3 % 2 = ', pow(3,3,2))
print('3 x 3 x 3 % 4 = ', pow(3,3,4))
输出:
2 x 2 % 2 = 0
3 x 3 % 2 = 1
3 x 3 x 3 % 2 = 1
3 x 3 x 3 % 4 = 3
**
运算符是pow()
方法的缩写形式,如下所示。
print('2 x 2 = ', 2**2)
print('3 x 3 = ', 3**2)
print('3 x 3 x 3 = ', 3**3)
print('3 x 3 x 3 x 3 = ', 3**4)
print('10 x 10 = ', 10**2)
print('1/(10 x 10) = ', 10**-2)
输出:
2 x 2 = 4
3 x 3 = 9
3 x 3 x 3 = 27
3 x 3 x 3 x 3 = 81
10 x 10 = 100
1/(10 x 10) = 0.01