Python math.pow(x, y):获取 x 的 y 次方 函数详解

  • Post category:Python

math.pow(x, y)函数的作用与使用方法

math.pow(x, y)函数返回x的y次幂。

使用方法

在Python中,要使用math.pow(x, y)函数,首先需要导入math模块。然后使用函数,传入两个参数x和y。

import math

result = math.pow(x, y)

示例1:

import math

x = 2
y = 3

result = math.pow(x, y)

print(result)
# 输出:8.0

上述示例计算了数字2的3次幂,也就是2的立方。结果为8.0。

示例2:

import math

x = 3
y = 2

result = math.pow(x, y)

print(result)
# 输出:9.0

本示例计算了数字3的2次幂,也就是3的平方。结果为9.0。

需要注意的是,math.pow(x, y) 函数返回浮点数。也就是说,如果要得到整数结果,需要进行转换。例如:

import math

x = 2
y = 3

result = math.pow(x, y)

print(int(result))
# 输出:8