I am having problem with random number generation in c#. If I RUN this form application directly, the random number generation is same for all.
If i DEBUG this line by line by pressing F10, then it will generate different random numbers. Why this is happening? What should I do to generate different random numbers?
Greyhound.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ADayAtTheRaces
{
class Greyhound
{
int location=0;
Random randomize = new Random();
public int run()
{
location = randomize.Next(0, 100);
return location;
}
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace ADayAtTheRaces
{
public partial class Form1 : Form
{
Greyhound[] greyHound = new Greyhound[4];
ProgressBar[] progressBar = new ProgressBar[4];
public Form1()
{
InitializeComponent();
for (int i = 0; i < 4; i++)
{
greyHound[i] = new Greyhound();
}
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i <= 3; i++)
{
progressBar[i].Value = greyHound[i].run();
}
}
}
}
This is because MATLAB's random number generator is initialized to the same state each time MATLAB starts up. If you wish to generate different random values in each MATLAB session, you can use the system clock to initialize the random number generator once at the beginning of each MATLAB session.
The rand() and srand() functions are used to generate random numbers in C/C++ programming languages. The rand() function gives same results on every execution because the srand() value is fixed to 1. If we use time function from time.
No, while nothing in computing is truly random, the algorithms that are used to create these "random" numbers are make it seem random so you will never get a repeating pattern.
Don't instantiate a new Random
object each time, instead use it as a static
member:
class Greyhound
{
static Random randomize = new Random();
int location=0;
public int run()
{
location = randomize.Next(0, 100);
return location;
}
}
See Random.Next returns always the same values
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With