简体   繁体   English

使用JS的阶乘函数

[英]Factorial function using JS

I wrote a code that accepts numbers and prints their factorial to the console. 我写了一个接受数字的代码,并将其阶乘打印到控制台。

This time, I wanna make it PROMPT a user for the number and then ALERT the factorial. 这次,我想让它提示用户输入该数字,然后警告阶乘。

 var x = prompt("Input the number" ); var y=1; function factorial(x) { for(i=2; i<=x; i++) { y *= i; } console.log(y); } alert(factorial(x)); 

Your code is almost correct, you only forgot to actually return the value of y as the result of your function. 您的代码几乎是正确的,只是忘记了实际返回y的值作为函数的结果。

 var x = prompt("Input the number" ); var y=1; function factorial(x) { for(i=2; i<=x; i++) { y *= i; } console.log(y); return y; } alert(factorial(x)); 

Note the return y statement I have added. 请注意我添加的return y语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM