简体   繁体   English

如何创建计算 6Factor 的 For 循环

[英]How to Create a For-Loop that calculates 6Factorial

To do this you must multiply 6*5*4*3*2*1.为此,您必须乘以 6*5*4*3*2*1。 To verify your loop is working correctly, the value you are looking for as a result is: 720为了验证您的循环是否正常工作,您正在寻找的值是: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 .我不完全确定你想用你拥有的代码做什么,它会简单地检查从 0 到 6 的所有数字,并输出乘以 7 时等于720

Since the highest value you'll get is 6 x 7 = 42 (nowhere near 720 ), you'll see nothing.因为你会得到的最高值是6 x 7 = 42 (远不720 ),你会看到什么。

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:将其转换为 Javascript(或任何与此相关的过程语言)应该相当简单,例如:

 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.尽量不要试验比 6 大得多的数字。

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

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