factorial of a number

前端 未结 28 2406
滥情空心
滥情空心 2020-12-09 11:57

I have the following code but it is not giving perfect result for factorial can u find it out plz



        
相关标签:
28条回答
  • 2020-12-09 12:52

    What about:

    function fact(n) {
      n = Math.round(n);
      if (n < 2) {
        return 1;
      }
      else {
        return n * fact(n - 1);
      }
    }
    

    ?

    0 讨论(0)
  • 2020-12-09 12:53

    You need to have a return in your function in the first place. ;)

    0 讨论(0)
  • 2020-12-09 12:54
    function factorial (n) {
      if (n > 1) {
        return n * factorial(n-1);
      }
      return 1;
    }
    console.log("recursive way => ",factorial(5)); 
    
    0 讨论(0)
  • 2020-12-09 12:55

    i am quite new to javascript and would be happy to know any improvements that could be made to this answer

    var a = 1;
    function factorial(num) {
        if (num == 0) {
            return 1;
        } else if (num < 0) {
            return undefined;
        } else {
        for(i = num; i > 0; i--){
            a *= i;
        }
        return a;
        }
    }
    var b = factorial(5);
    console.log(b);

    0 讨论(0)
提交回复
热议问题