Random number generator always picks the same value when run inside a loop

后端 未结 5 899
慢半拍i
慢半拍i 2020-11-30 14:15

The problem with the code is, when I try to generate a number, if the spin is equal 1 it generates values inside range (1,2,3) if if try to use the loop to sum random values

5条回答
  •  粉色の甜心
    2020-11-30 15:11

    You need to initialize your Random object, then call Next() inside your loop.

    i.e.

    if (toggled3.Checked)
    {
      // initialize your total and the random number generator
      int diceTotal = 0;
      Random rand = new Random();
    
      for (int i = 0; i < spind3.Value; i++)
      {
        // add the next random number between 1 and 3
        diceTotal += rand.Next(1, 4); 
      }
    }
    

提交回复
热议问题