在JavaScript中实现Math函数并返回m ^ n
我们需要编写一个JavaScript函数,该函数接受两个数字,即m和n。然后函数应该计算并返回m^n。
例如-对于m=4,n=3,则
power(4, 3) = 4^3 = 4 * 4 * 4 = 64 power(6, 3) = 216
下面的代码将使用power()JavaScript中的函数-
示例
const power = (m, n) => {
if(n < 0 && m !== 0){
return power(1/m, n*-1);
};
if(n === 0){
return 1;
}
if(n === 1){
return m;
};
if (n % 2 === 0){
const res = power(m, n / 2);
return res * res;
}else{
return power(m, n - 1) * m;
};
};
console.log(power(4, 3));
console.log(power(6, 3));输出结果
控制台中的输出将是-
64 216
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿