硬币翻转和反击Javascript

时间:2018-03-04 22:43:36

标签: javascript loops

所以我试图让这个硬币翻转,但它一直在翻转...当我希望它在10次之后停止。我还需要一个计数器变量来告诉我翻转它的次数。

var coin = randomNumber (0,1);

write (coin);
while (coin < 10) {
  coin = randomNumber (0,1);
  write (coin);
}

2 个答案:

答案 0 :(得分:0)

最简单的方法是使用for循环。

for (var i = 0; i < 10; i++) {
  var coin = randomNumber (0, 1);
  write (coin);
}

有关详情,请参阅此处:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration

如果你想坚持while循环:

var timesFlipped = 0;
while (timesFlipped < 10) {
  var coin = randomNumber (0, 1);
  write (coin);
  timesFlipped = timesFlipped + 1;  // alternatively: timesFlipped++;
}

答案 1 :(得分:0)

您尚未向我们展示您的randomNumber函数,但它可能只生成小于10的数字。由于while循环表示只要coin小于10就会继续运行,因此循环将永远存在。

while循环因产生无限循环而臭名昭着。我个人从不使用它们。由于您知道需要循环多少次,因此计数循环是正确的选择。

以下是您的需求:

// Write the function that gets random number and report the results a certain number of times:
function coinToss(numTimes) {
  // Instead of a while loop, use a counting loop that will 
  // have a definite end point
  for(var i = 0; i < numTimes; i++){

    // Get a random number from 0 to 1
    var coin = Math.floor(Math.random() * 10);

    // Test to see if it is even or odd by checking to see if
    // it is divisible by 2 with no remainder.
    var even = (coin % 2 === 0);

    // Report the results
    console.log("The coin was " + (even ? "heads " : " tails"));
  }
}

// Now, call the function and tell it how many times to loop
coinToss(10);