随机数生成问题 [英] Random Number generation Problem

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

问题描述





任何人都可以告诉我如何生成随机数,这样在每次执行时它都不应该生成相同的数字或相同的数字。

Hi,

Can anyone tell me how to generate random numbers so that on every execution it should not generate identical numbers or same numbers.

推荐答案

随机数从种子值开始:通常是系统时钟。所以,只要你不同时启动随机数生成器,你应该做什么并不重要!



在C#中,它很简单:a Random类的类级别(甚至可能是 static )实例:

Random numbers are started from a seed value: normally the system clock. So it shouldn't matter what you do as long as you don't start the random number generator at the same time!

In C#, it's pretty easy: a class level (possibly even static) instance of the Random class:
private Random rand = new Random();



然后用它来生成你的你想要的数字:


Then use it to generate your numbers when you want:

for (int i = 0; i < 100; i++)
   {
   int r = rand.Next();
   Console.WriteLine(r);
   }

应该证明每次执行代码的顺序都不同。



如果你想要一个唯一的编号执行,然后我建议使用Guid:

Should prove the sequence is different for each execution of your code.

If you want a single unique number for each execution, then Id suggest using a Guid instead:

Guid id = Guid.NewGuid();

因为这些非常非常不太可能复制。

as these are very, very unlikely to be duplicated.


只需使用.NET中的Random类

确保在每个会话中使用不同的种子。



http://msdn.microsoft。 com / en-us / library / ctssatww(v = vs.110).aspx [ ^ ]



使用相同的种子将导致随机生成器class再次创建相同的序列。
Just use the Random class in .NET
make sure you use a different "seed" on each session.

http://msdn.microsoft.com/en-us/library/ctssatww(v=vs.110).aspx[^]

using the same "seed" will cause the Random generator class to create the same sequence again.


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

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