0
所以我剛剛開始學習C#,並且我在本練習中得到了N次滾動模,然後打印每個滾動的次數。我得到了答案,但是,我的問題在於在循環前和循環中實例化一個Random
數字對象。在for循環之前實例化和在for循環中實例化之間的區別
我的代碼是這樣的(這是循環之前實例化):
static void DiceRoll(int RollTimes)
{
int roll = 0;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
Random rnd = new Random();
for (int ctr = 0; ctr < RollTimes; ctr++)
{
roll = 0;
roll = (int)rnd.Next(1, 7);
switch (roll)
{
case 1:
counter1++;
break;
case 2:
counter2++;
break;
case 3:
counter3++;
break;
case 4:
counter4++;
break;
case 5:
counter5++;
break;
case 6:
counter6++;
break;
}
}
Console.WriteLine("1 is rolled {0} times.", counter1);
Console.WriteLine("2 is rolled {0} times.", counter2);
Console.WriteLine("3 is rolled {0} times.", counter3);
Console.WriteLine("4 is rolled {0} times.", counter4);
Console.WriteLine("5 is rolled {0} times.", counter5);
Console.WriteLine("6 is rolled {0} times.", counter6);
}
,結果是這樣的:
1 is rolled A times.
2 is rolled B times.
3 is rolled C times.
4 is rolled D times.
5 is rolled E times.
6 is rolled F times.
我之前正確的,實例化線(Random rnd = new Random();
)在循環中。
for (int ctr = 0; ctr < RollTimes; ctr++)
{
roll = 0;
roll = (int)rnd.Next(1, 7);
Random rnd = new Random();
// rest of the code
那麼結果(任意):
1 is rolled (N) times.
2 is rolled (N) times.
3 is rolled (N) times.
4 is rolled (N) times.
5 is rolled (N) times.
6 is rolled (N) times.
有人可以解釋爲什麼實例的位置改變的結果告訴我嗎?謝謝!