D
D
Denis2015-07-07 09:28:12
C++ / C#
Denis, 2015-07-07 09:28:12

C# Why does random always output the same numbers?

Good afternoon.
Just started learning C#.
You need to make a random number generator. It turns out this code:

Random randM = new Random();
            Random randV = new Random();
            Random randL = new Random();

            Mas = randMt.Next(1, 7)+6;
            label6.Text = String.Format("{0}", Mas);
                        
            Vin = randV.Next(2, 13) + 12;
            label7.Text = String.Format("{0}", Vin);
                        
            Ud = randL.Next(1, 7) + 6;
            label8.Text = String.Format("{0}", Ud);

The result of the output is always one number, i.e. for example
Mas = 8
Vin = 16
Ud = 8
And I want to have different numbers, please tell me where I'm wrong.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Silin, 2015-07-07
@foma24

Um... honestly speaking it's strange... It will be necessary to dig.
To make it work, do this:

Random rand = new Random();
Mas = rand.Next(1, 7)+6;
label6.Text = Mas.ToString();
                        
Vin = rand.Next(2, 13) + 12;
label7.Text = Vin.ToString();
                        
Ud = rand.Next(1, 7) + 6;
label8.Text = Ud.ToString();

There is no need to create 3 randoms, you can use one everywhere.

N
nfrey, 2015-07-08
@nfrey

new Random creates an instance of the random, which depends on the number of ticks in the system (clock). If you create several objects at the same time, they will return the same values ​​to you.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question