How do I use random numbers in C#?

半世苍凉 提交于 2020-01-03 14:11:18

问题


I'm working on Pong in C# w/ XNA.

I want to use a random number (within a range) to determine things such as whether or not the ball rebounds straight, or at an angle, and how fast the ball moves when it hits a paddle.

I want to know how to implement it.


回答1:


Use the Random class. For example:

Random r = new Random();
int nextValue = r.Next(0, 100); // Returns a random number from 0-99



回答2:


Unless you need cryptographically secure numbers, Random should be fine for you... but there are two gotchas to be aware of:

  • You shouldn't create a new instance every time you need one. If you create an instance without specifying a seed, it will use the current time as the seed - which means if you create several instances in quick succession, many of them will produce the same sequence of numbers. Typically you create a long-lasting instance of Random and reuse it.
  • It's not thread-safe. If you need to generate random numbers from multiple threads, you should think about having one instance per thread. Read this blog post for more information - but make sure you read the comments as well, as they have very useful information.



回答3:


Random rnd = new Random();
rnd.Next(minValue, maxValue);

i.e.

rnd.Next(1,10);



回答4:


Use the Random object's Next method that takes a min and max and returns a value in that range:

var random = new Random();    
int randomNum = random.Next(min, max);



回答5:


While you can use the Random class like all the other are suggesting, the Random class only uses psuedo-random number generation. The RandomNumberGenerator, which can be found in the System.Security.Cryptography namespace, creates actual random numbers.

How To Use:

RandomNumberGenerator rng = RandomNumberGenerator.Create();
byte[] rand = new byte[25]; //Set the length of this array to
                           // the number of random numbers you want
rng.GetBytes(rand);

More Info: http://msdn.microsoft.com/en-us/library/system.security.cryptography.randomnumbergenerator(v=VS.80).aspx




回答6:


Here is my random generator

 private static Random rnd = new Random(Environment.TickCount);

 private int RandomNum(int Lower, int Upper)
{

 return rnd.Next(Lower, Upper);//MyRandomNumber;

}


来源:https://stackoverflow.com/questions/3217651/how-do-i-use-random-numbers-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!