📜  Python中的 pow()

📅  最后修改于: 2022-05-13 01:54:44.806000             🧑  作者: Mango

Python中的 pow()

Python pow()函数返回给定数字的幂。此函数计算 x**y 。此函数首先将其参数转换为浮点数,然后计算幂。

Python pow() 示例

示例 1:pow() 的工作

Python3
# Python code to demonstrate pow()
# version 1
 
print("The value of 3**4 is : ", end="")
 
# Returns 81
print(pow(3, 4))


Python3
# Python code to demonstrate pow()
# version 2
 
print("The value of (3**4) % 10 is : ", end="")
 
# Returns 81%10
# Returns 1
print(pow(3, 4, 10))


Python3
# Python code to discuss negative
# and non-negative cases
 
# positive x, positive y (x**y)
print("Positive x and positive y : ", end="")
print(pow(4, 3))
 
print("Negative x and positive y : ", end="")
# negative x, positive y (-x**y)
print(pow(-4, 3))
 
print("Positive x and negative y : ", end="")
# positive x, negative y (x**-y)
print(pow(4, -3))
 
print("Negative x and negative y : ", end="")
# negative x, negative y (-x**-y)
print(pow(-4, -3))


输出:

The value of 3**4 is : 81.0

示例 2:具有三个参数的Python pow()

float pow(x,y,mod)函数计算 (x**y) % mod 。此函数首先将其参数转换为浮点数,然后计算幂。

Python3

# Python code to demonstrate pow()
# version 2
 
print("The value of (3**4) % 10 is : ", end="")
 
# Returns 81%10
# Returns 1
print(pow(3, 4, 10))

输出:

The value of (3**4) % 10 is : 1

pow() 中的实现案例:

Python3

# Python code to discuss negative
# and non-negative cases
 
# positive x, positive y (x**y)
print("Positive x and positive y : ", end="")
print(pow(4, 3))
 
print("Negative x and positive y : ", end="")
# negative x, positive y (-x**y)
print(pow(-4, 3))
 
print("Positive x and negative y : ", end="")
# positive x, negative y (x**-y)
print(pow(4, -3))
 
print("Negative x and negative y : ", end="")
# negative x, negative y (-x**-y)
print(pow(-4, -3))

输出:

Positive x and positive y : 64
Negative x and positive y : -64
Positive x and negative y : 0.015625
Negative x and negative y : -0.015625