For creating a list with 100 random number between 0 and 1 I wrote below code that I receive the error.
public List<float> random()
{
List<float> storerandomvalues = new List<float>(100);
Random randomvalues = new Random();
float randomnum;
for (int counter = 0; counter < 100; counter++)
{
randomnum = 0f;
randomnum = randomvalues.Next(1);
storerandomvalues[counter]= randomnum; //the error
}
return storerandomvalues;
}
You're creating empty storerandomvalues (without any items). Parameter in the List<> constructor is the list capacity only.
The best solution in your case is to use array instead of List<> (because in your case the number of items in the collection is constant):
var storerandomvalues = new int[100];
Random randomvalues = new Random();
float randomnum;
for (int counter = 0; counter < storerandomvalues.Length; counter++)
{
randomnum = 0f;
randomnum = randomvalues.Next(1);
storerandomvalues[counter] = randomnum;
}
return storerandomvalues;
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