我设计的自定义幂函数有什么问题(javascript)?
whats the problem with the custom power function I designed(javascript)?
建议的问题是基于计算数字的小数幂的问题,但我只是希望它是整数 form.The 函数 power 正确显示了一个数的幂 b 但是它没有按预期停止它应该 be.When 我尝试 return 总和作为 return 函数末尾的总和 power 它只是加载并且没有显示任何东西请帮助 me.Any帮助会很大 appreciated.I 无法使用内置的 pow() function.Thanks.
function power(a, b) {
a = parseInt(a);
b = parseInt(b);
var sum = 1;
var result;
var pow = 1;
for (var i = 1; i <= b; i++) {
pow = 1;
if (i == 1) {
pow = a * i;
sum = 1;
} else {
i--;
pow = a * i;
sum = sum * pow;
alert(sum);
}
}
}
var a = prompt("Enter the number a for calculating its power?");
var b = prompt("Enter the number for calculating pow of a i.e enter power of a");
var answer = power(a, b);
alert("a^b is equal to : " + answer);
如果您对递归函数调用感兴趣,请查看此内容。,
var power = function(a, b)
{
a = parseInt(a);
b = parseInt(b);
if (b === 0)
{
return 1;
}
else
{
return a * power(a, b-1);
}
};
var a = prompt("Enter the number a for calculating its power?");
var b = prompt("Enter the number for calculating pow of a i.e enter power of a");
alert("the result "+ a + " ^ " + b + " is " + power(a, b));
建议的问题是基于计算数字的小数幂的问题,但我只是希望它是整数 form.The 函数 power 正确显示了一个数的幂 b 但是它没有按预期停止它应该 be.When 我尝试 return 总和作为 return 函数末尾的总和 power 它只是加载并且没有显示任何东西请帮助 me.Any帮助会很大 appreciated.I 无法使用内置的 pow() function.Thanks.
function power(a, b) {
a = parseInt(a);
b = parseInt(b);
var sum = 1;
var result;
var pow = 1;
for (var i = 1; i <= b; i++) {
pow = 1;
if (i == 1) {
pow = a * i;
sum = 1;
} else {
i--;
pow = a * i;
sum = sum * pow;
alert(sum);
}
}
}
var a = prompt("Enter the number a for calculating its power?");
var b = prompt("Enter the number for calculating pow of a i.e enter power of a");
var answer = power(a, b);
alert("a^b is equal to : " + answer);
如果您对递归函数调用感兴趣,请查看此内容。,
var power = function(a, b)
{
a = parseInt(a);
b = parseInt(b);
if (b === 0)
{
return 1;
}
else
{
return a * power(a, b-1);
}
};
var a = prompt("Enter the number a for calculating its power?");
var b = prompt("Enter the number for calculating pow of a i.e enter power of a");
alert("the result "+ a + " ^ " + b + " is " + power(a, b));