如何在C#中随机编号随机数 [英] How to make a random number random in C#
问题描述
随机ranNum = new Random();
string colorName =pic+ arrayColors [ranNum.Next(0,6)];
我在ASP.NET中尝试了这个代码,但是在for循环中,但是每个循环的随机数似乎保持不变。如何使每个循环不同?
问题通常是每次都在创建一个新的Random类实例 - 当你这样做时,它是从系统时钟初始化的,如果你在一起创建它们,你每次都会得到相同的随机序列。
为了避免这种情况,在类级声明你的Random对象:
private Random ranNum = new Random();并在每次需要新的随机数时使用相同的实例。
Random
获取种子值这将混淆起点:
随机r = = 新随机( new System.DateTime()。毫秒);
正如Jibesh所说,把
Random ranNum = new 随机();
for循环外的
这个里面
string colorName = pic + arrayColors [ranNum.Next( 0 , 6 )];
--------------------------------
CODE
------------------------------------ < pre lang =c#> Random ranNum = new Random();
for (i = 0 ; i< 10; i ++){
string colorName = pic + arrayColors [ranNum.Next( 0 , 6 )];
}
添加的代码块[/ Edit]
Random ranNum = new Random();
string colorName= "pic" + arrayColors[ranNum.Next(0, 6)];
I tried this code in ASP.NET but in a for loop but the random number seems to stay the same for each loop. How can I make it different for each loop?
The problem is generally that you are creating a new instance of the Random class each time - when you do this, it is initialised from the system clock, and if you create them close together you will get the same "random" sequence each time.
To avoid that, declare your Random object at class level:
private Random ranNum = new Random();and use the same instance each time you want a new random number.
Random
takes a seed value which will mix up the start point:
Random r = = new Random(new System.DateTime().Millisecond);
As Jibesh said, put
Random ranNum = new Random();
outside the for loop
and this inside
string colorName= "pic" + arrayColors[ranNum.Next(0, 6)];
--------------------------------
CODE
------------------------------------Random ranNum = new Random(); for (i = 0;i<10;i++){ string colorName= "pic" + arrayColors[ranNum.Next(0, 6)]; }
[Edit]Code blocks added[/Edit]
这篇关于如何在C#中随机编号随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!