2

私はJavascriptを初めて使用し、whileループで頭を包み込もうとしています。私は彼らの目的を理解していて、彼らがどのように機能するかは理解していると思いますが、私は彼らに問題を抱えています。

while値は、2つの乱数が互いに一致するまで繰り返されるようにします。現在、whileループは1回だけ実行されます。繰り返し実行する場合は、もう一度実行する必要があります。

diceRollValue === compGuessになるまでifステートメントが自動的に繰り返されるように、このループを設定するにはどうすればよいですか?ありがとう。

diceRollValue = Math.floor(Math.random()*7);
compGuess = Math.floor(Math.random()*7);
whileValue = true;

while (whileValue) {
    if (diceRollValue === compGuess) {
        console.log("Computer got it right!")
        whileValue = false;
    }
    else {
        console.log("Wrong. Value was "+diceRollValue);
        whileValue = false;
    }
}
4

3 に答える 3

6

これは、しばらくの間だけ乱数ジェネレーターを実行しているためです。2つの新しい数値が必要な場合は、whileステートメント内で実行する必要があります。次のようなもの:

var diceRollValue = Math.floor(Math.random() * 7),
    compGuess = Math.floor(Math.random() * 7),
    whileValue = true;
while (whileValue){
  if (diceRollValue == compGuess){
    console.log('Computer got it right!');
    whileValue = false; // exit while
  } else {
    console.log('Wrong. Value was ' + diceRollValue);
    diceRollValue = Math.floor(Math.random() * 7); // Grab new number
    //whileValue = true; // no need for this; as long as it's true
                         // we're still within the while statement
  }
}

リファクタリングしたい場合はbreak、(変数を使用する代わりに)ループを終了するために使用することもできます。

var diceRollValue = Math.floor(Math.random() * 7),
    compGuess = Math.floor(Math.random() * 7);
while (true){
  if (diceRollValue == compGuess){
    // breaking now prevents the code below from executing
    // which is why the "success" message can reside outside of the loop.
    break;
  }
  compGuess = Math.floor(Math.random() * 7);
  console.log('Wrong. Value was ' + diceRollValue);
}
console.log('Computer got it right!');
于 2012-10-18T02:29:44.993 に答える
1

2つの問題があります。1つはwhileValue、ifブロックとelseブロックの両方で設定しているため、乱数の値に関係なく、1回の反復後にループが中断することです。

次に、ループの前に推測を生成しているため、同じ値を何度もチェックします。

したがってwhileValue、elseブロックの割り当てを削除し、compGuess割り当てをwhileループに移動します。

于 2012-10-18T02:35:12.063 に答える
1

2つの確率変数をループ内に配置します。

whileValue = true;

while (whileValue) {
    diceRollValue = Math.floor(Math.random()*7);
    compGuess = Math.floor(Math.random()*7);
    if (diceRollValue === compGuess) {
        console.log("Computer got it right!")
        whileValue = false;
    }
    else {
        console.log("Wrong. Value was "+diceRollValue);
    }
}
于 2012-10-18T02:39:34.350 に答える