简体   繁体   中英

3 digit random number in C#

Is there a better way to generate 3 digit random number than the following:

var now = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture);
string my3digitrandomnumber = now.Substring(now.Length - 7, 3);

Thanks..

Yes - your current code isn't random at all. It's based on the system time. In particular, if you use this from several threads at the same time - or even several times within the same thread in quick succession - you'll get the same number each time.

You should be using Random or RandomNumberGenerator (which is more secure).

For example, once you've got an instance of Random , you could use:

int value = rng.Next(1000);
string text = value.ToString("000");

(That's assuming you want the digits as text. If you want an integer which is guaranteed to be three digits, use rng.Next(100, 1000) .)

However, there are caveats around Random :

  • You don't want to create a new instance each time you use it; that would also be time based unless you specify a seed
  • It's not thread-safe

So ideally you probably want one per thread. My article on randomness talks more about this and gives some sample code.

您可以使用Random类并调用Next(10)三次。

int r = (new Random()).Next(100, 1000);

Well, firstly that's an odd setup you have there, why do you first get the date?

You should use this to get a number of 3 digits (less than 1000).

Random rand = new Random(); // <-- Make this static somewhere

const int maxValue = 999;
string number = rand.Next(maxValue + 1).ToString("D3"); 

The maxValue + 1 is because the paramter for Random.Next(int) is an exclusive upper bound, meaning that the number returned will always be less than the parameter. It can never be equal to it.

new Random.NextDouble() * 1000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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