如何创建2个随机值 [英] How do you create 2 random values

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

问题描述

我写了


但是dieOne和dieTwo总是相等的,您如何制作两个独立的随机值?

<感谢> Mikanu ,现在可以使用了.

在2009年7月13日星期一10:43 PM修改

解决方案

您应创建一个Random实例作为类的静态字段,并在需要时使用它.
它永远不应是方法的局部变量.


正确的方法是创建 Random 类的实例,然后调用以下方法之一:
-Next(Int32 max) // will return a random number smaller than max
-NextByte() // will return a random byte (between 0 and 255)
-NextDouble() // will return a random number between 0.0 and 1.0<br />

这是一个代码示例,它将生成介于0和10之间的两个随机数a和b

<br />Random rnd = new Random();<br />int a = rnd.Next(10);<br />int b = rng.Next(10);<br />




I wrote

<br />            Random RollOne = new Random();<br />            Random RollTwo = new Random();<br />                dieOne = RollOne.Next(1, 7);<br />                dieTwo = RollTwo.Next(1 , 7);<br />                sum = dieOne + dieTwo;<br />



but dieOne and dieTwo are always equal, how do you make two independent random values?

Edit:
Thanks Mikanu, it works now.

modified on Monday, July 13, 2009 10:43 PM

解决方案

You should create one instance of Random as a static field of the class and use it whenever you need it.
It should never be a local variable of a method.


The correct way to do that is to create an instance of the Random class and then call one of the following methods:
- Next(Int32 max) // will return a random number smaller than max
- NextByte() // will return a random byte (between 0 and 255)
- NextDouble() // will return a random number between 0.0 and 1.0<br />

Here''s a code sample which will generate two random numbers, a and b, between 0 and 10

<br />Random rnd = new Random();<br />int a = rnd.Next(10);<br />int b = rng.Next(10);<br />




这篇关于如何创建2个随机值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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