开发者

C# Random Numbers [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the h开发者_Go百科elp center. Closed 12 years ago.

Ok, So Im using int indexSelector = RandomNumber(1, 14); to create a random number and pull the matching index out of an array. But it seems to only be calling 3 or 4 numbers. Like the items being pulled out are very similar.

Whats going on?


It sounds like you are calling a function which re-creates a Random object on each call. Don't re-create your Random object on each function call.

So do something like this:

private Random random = new Random();
public int RandomNumber(int min, int max)
{
  return random.Next(min, max); 
}


Make your random variable static:

static Random random = new Random();


Per Brian's suggestion, define your Random object somewhere where it won't be recreated:

Random r = new Random();

And use this to get the number:

int indexSelector = r.Next(1, 14);


Random if provided by the same seed, always returns the same sequence of numbers. I suggest you initialise your Random using a seed:

            Random r = new Random(Environment.TickCount);

Or even better:

            Random r2 = new Random(BitConverter.ToInt32(Guid.NewGuid().ToByteArray(), 0));

This ensures that you create a really random number sequence. If you do not send a seed, system will use a time dependent seed which will be the same if you create them immediately after each other.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜