阶乘不会相乘

时间:2019-05-01 23:04:00

标签: javascript

运行代码时,它不会乘以我的数字,只是循环输出直到达到1

我尝试了多种不同的方法,而这是我获得的最接近的方法

    ......................................
    var BR="<br />"; //html line break

    function factorial(Num) {

   document.write("The factorial of your number is" +Num +BR);

   if (Num == 1 ) return 1;

   else return (Num * factorial(Num-1));

    }
.....................................................        





   .......................................
        var Num; //users number
        var Numfactorial;
        var ES="";
               var factorial                     
        Num=prompt("Enter a number between 1-20" +ES);
        Numfactorial=factorial(Num);
     .........................................   

应该将数字乘以下来,所以说您输入20,它应该向下移19 * 18 * 17 ...向下乘以1,然后输出乘积。

2 个答案:

答案 0 :(得分:0)

document.write放在函数之外,然后仅将结果(Numfactorial)打印到页面上。您还需要将Num解析为一个数字,然后删除var factorial

var BR = "<br />";
function factorial(Num) {
    if (Num == 1) return 1;
    else return Num * factorial(Num - 1);
}
var Num;
var Numfactorial;
var ES = "";
Num = parseInt(prompt("Enter a number between 1-20" + ES));
Numfactorial = factorial(Num);
document.write("The factorial of your number is " + Numfactorial + BR);

答案 1 :(得分:0)

好吧,这就是代码的预期输出。函数阶乘正在返回您未使用的值以显示该值。您应该这样写:

....................................................
var BR="<br />"; //html line break
function factorial(Num) {
   if (Num == 1 ) return 1;
   else return (Num * factorial(Num-1));
}
.....................................................



.......................................
    var Num; //users number
    var Numfactorial;
    var ES="";
           var factorial                     
    Num=prompt("Enter a number between 1-20" +ES);
    Numfactorial=factorial(Num);
    document.write("The factorial of your number is" +Numfactorial +BR);
 .........................................