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

后端 未结 5 907
慢半拍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:03

    The problem is that you are creating random generators too close in time. The random generator constructor uses the current time to seed the generator, and when you create them too close in time they will all be seeded using the same time.

    Create one random generator and use in the loop:

    Random rnd = new Random();
    for (int i = 1; i <= spind3.Value; i++) {
      diceCalc[1] += rnd.Next(1, 4);
    }
    

提交回复
热议问题