硬币翻转和反击Javascript

问题描述 投票:0回答:2

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

var coin = randomNumber (0,1);

write (coin);
while (coin < 10) {
  coin = randomNumber (0,1);
  write (coin);
}
javascript loops
2个回答
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++;
}

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);
© www.soinside.com 2019 - 2024. All rights reserved.