简体   繁体   中英

How to Create a For-Loop that calculates 6Factorial

To do this you must multiply 6*5*4*3*2*1. To verify your loop is working correctly, the value you are looking for as a result is: 720

var dvDDG = document.querySelector("#ddg");

for(var i = 0; i < 7; i++) {


  //remainder..

    if( (i*7) == 720 ) {
        dvDDG.innerHTML += i +   "<br />";
    }
}

I'm not entirely certain what you're trying to do with the code you have, it will simply check all numbers zero through six inclusive, and output the value which, when multiplied by seven, is equal to 720 .

Since the highest value you'll get is 6 x 7 = 42 (nowhere near 720 ), you'll see nothing.

The pseudo-code for what you're after would be along the lines of:

fact = 1
for i = 2 to N inclusive:
    fact = fact * i
print fact

Turning that into Javascript (or any procedural language for that matter) should be fairly simple, such as with:

 function fact(n) { res = 1 for (var i = 2; i <= n; i++) { res = res * i; } return res } alert(fact(6))

It's fairly simple:

var factorial = 1;
var num = 6;
for (var i = 1; i <= num; i++){
  factorial *= i;
}

There you go, your answer is the variable factorial. Just copy it into any output function you want. Be careful though, factorial can get pretty huge very fast. Try not to experiment on numbers that much larger that 6.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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