简体   繁体   English

C#中的随机数

[英]Random numbers in c#

i use 我用

Random rnd = new Random();
x=rnd.Next(10);

but every time i get the same number. 但是每次我得到相同的数字。 how to fix it and get different numbers? 如何解决并获得不同的数字? Tell me easy method. 告诉我简单的方法。

thanks. 谢谢。 sorry for bad english. 对不起,英语不好。

Random's default constructor uses the current time as its seed. Random的默认构造函数使用当前时间作为其种子。 Therefore, if you initialize multiple Random objects in rapid succession (such as in a loop, for instance), they will share the same seed. 因此,如果您快速连续地初始化多个Random对象(例如,在循环中),则它们将共享相同的种子。

Create your Random object once and use it multiple time, or create a seed beforehand and use it to initialize your generators. 一次创建您的Random对象并多次使用它,或者预先创建一个种子并使用它来初始化生成器。

MSDN explicitly addresses this "problem" in the remarks section of the MSDN docs for the Random class, including a sample! MSDN在用于随机类的MSDN文档的备注部分中明确解决了该“问题”,其中包括一个示例!

http://msdn.microsoft.com/en-us/library/system.random.aspx http://msdn.microsoft.com/en-us/library/system.random.aspx

Obligatory XKCD reference: 强制性XKCD参考:

http://xkcd.com/221/ http://xkcd.com/221/

Make sure you use the constructor only once. 确保只使用一次构造函数。 You can add a seed. 您可以添加种子。

Random rnd  = new Random(DateTime.Now.Millisecond);

Then you can make calls to as you actually did it. 然后,您可以像实际操作那样拨打电话。

x=rnd.Next(10);

But make sure you don't have the constructor and the call to the Next() method inside a loop or something similar... 但是请确保在循环或类似内容中没有构造函数和对Next()方法的调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM