js实现阶乘

2017-12-19  本文已影响0人  My康

//while循环实现

function calNum(n) {

var product = 1;

while(n > 1){//1*5*4*3*2,1*n*(n-1)*(n-2)*...*2

product *= n;

n--;

}

return product;

}

console.log(calNum(5))


function calNum(n){

var a = 1, str = '1*';

for (var i = 2; i <= n; i++) {

str += i + '*';

a *= i;

}

str = str.substr(0,str.length-1);

return str + '=' +a;

}

console.log(calNum(5));

上一篇 下一篇

猜你喜欢

热点阅读