2017-07-07 8 views
0
using System; 

namespace SeventhConsoleProject 
{ 
    class MainClass 
    { 
     public static void Main(string[] args) 
     { 
      Random NumGen = new Random(); 
      int diceRoll = 0; // The variable used to roll the dice 
      int attempts = 0; // The amount of times it takes Tom to get a 6 
      int amountmodifier = 10; //To edit the amount of times that the program loops so that I can get a more accurate average 

      Console.Write ("Tom wants to roll a dice multiple times and see how long it takes to get a 6.\nTom wants to get the average of " + amountmodifier + " successful attempts "); 
      Console.ReadKey(); 
      Console.WriteLine(); 

      for (int amount = 1; amount <= amountmodifier; amount++) { 
       while (diceRoll != 6) { 
        diceRoll = NumGen.Next (1, 7); 
        attempts++; 
       } 
      } 
      int averageafter = attempts/amountmodifier; 

      Console.WriteLine ("Over " + amountmodifier + " successful attempts it took Tom an average of " + averageafter + " attempts to get a 6"); 
      Console.ReadKey(); 
     } 
    } 
} 

私は最近Brackeyの7回目のビデオをc#のチュートリアルシリーズで見ました。私は彼がコメントに残した挑戦を完了しようとしています。forとwhile while brackeysからの混乱第7回チュートリアルビデオ

最初のタスクは、 "Tom"がサイコロを転がし、サイコロが6になるまでサイコロを動かし続けるプログラムを作成することでした。ユーザーは、 "Tom"を何回取得したかについて、彼が6を得る前にサイコロを振る。私が考え出した部分。

しかし、挑戦の部分は、 "トム"が6回転がって成功した10回の試行の平均を見つける方法を理解する必要があります。この部分は私を混乱させます。私のコードの背後にある私のロジックは、forループが変数を変更する回数を10回または何回か繰り返すことです。amountmodifierです。 forループがループを通過するたびに、 "Tom"が6回ロールバックするまでwhileループが続きます。 "Tom"ロールが6回ループし、forループは終了し、forループは別の時間に実行されます。 10回繰り返します。

私の考えでは、forループが完了した後、「試行回数」に10回の試行が成功し、その試行の平均を作成するために「amountmodifier」で除算されます。しかし、それは動作しません。私が結論できるものは、forループが10回繰り返されていないか、またはattemptsの量が常にリセットされていることです。なぜ私は理解できません。誰かが説明するなら、私は本当に感謝しています。

+0

は、読みやすくするために私の質問を編集するためにあなたのSoviutをありがとうございます。それは本当にあなたの素晴らしいです! – Skullgrabber

答えて

1

問題はここにある:

for (int amount = 1; amount <= amountmodifier; amount++) { 
    // Add this line: 
    diceRoll = 0; 

    while (diceRoll != 6) { 
     diceRoll = NumGen.Next (1, 7); 
     attempts++; 
    } 
} 

問題は、6が巻かれた後、diceRollの値が6だからfor次のループ処理では、あなたがすべてでwhileループに入ったことがないということですdiceRollはすでに6であるためです。diceRollが(当初のように)0にリセットされていることを示唆した行を追加することです。さらに良い

、あなたはどこか他のdiceRollを使用する必要がないので、ちょうどそこにそれを宣言するために、次のようになります。

for (int amount = 1; amount <= amountmodifier; amount++) { 
    int diceRoll = 0; // and get rid of the similar line at the top of Main 
+0

ありがとうございました。この問題は長い間私を混乱させていました。私はサイコロを気付かなかった。ロールが問題だった。あなたは本当に大きな頭痛から私を救った!私はどれほど感謝しているのか言葉にすることはできません。あなたは素晴らしいです! – Skullgrabber