随机数生成在C# [英] Random number generation in C#

查看:171
本文介绍了随机数生成在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在写的训练演习,其中我不得不创建随机矩形阵列一些C#代码。

I have been writing some C# code for a training exercise, in which I had to create an array of random rectangles.

问题在于矩形由生产我GetRandomRectangle功能总是相同的。我使用 System.Random 来生成矩形的坐标

Problem being that the rectangle being produced by my GetRandomRectangle function was always the same. I was using System.Random to generate the coordinates for the rectangle.

我已经意识到这是因为随机对象be​​ign使用默认构造函数创建的,所以有相同的种子。我已经修改了它来获取每个矩形不同的种子,现在,它工作正常。

I've realised that it was because the Random object was beign created with the default constructor, and so had the same seed. I've modified it to get a different seed for each rectangle now, and it works fine.

现在的问题是 - 它是如何决定的默认种子?我注意到,它似乎并没有随着时间的推移要么改变,种子2中创建一个矩形,将一直被赋予相同的尺寸。

The question is - how does it decide on the 'default seed'? I've noticed that it doesn't seem to change over time either, a rectangle created with seed 2 will always be given the same dimensions.

这也可能是东西,我可以谷歌,但它是很好的听取意见和信息,从你们为好。

It's probably something that I could Google, but it's nice to hear opinions and info from you guys as well.

感谢:)

推荐答案

默认种子取自系统时钟。

The default seed is taken from the system clock.

我猜你的 GetRandomRectangle 方法被称为临门和instantating一个新的实例的随机各一次。执行此操作时,随机的每个实例会从系统时钟,这就是为什么你的方法每次创建相同的矩形相同的种子。

I'm guessing that your GetRandomRectangle method was being called in quick succession and instantating a new instance of Random each time. When you do this, each instance of Random will take the same seed from the system clock, which is why your method created the same rectangle each time.

一种解决方案是创建有一个 随机实例并传递到你的方法:

One solution is to create one instance of Random and pass that into your method:

Random rng = new Random();

Rectangle foo = GetRandomRectangle(rng);
Rectangle bar = GetRandomRectangle(rng);
Rectangle baz = GetRandomRectangle(rng);

// ...

public Rectangle GetRandomRectangle(Random rng)
{
    // create the rectangle using rng
}

这篇关于随机数生成在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆