C#中的随机数 [英] Random number In C#

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

问题描述

可能的重复:
随机数生成器没有按照我计划的方式工作(C#)

我创建了一个返回随机数的方法:

I created a method that returns me a random number:

public static int SelectRandomMachine(int max)
{
int seed = (int)DateTime.Now.Ticks;
Random rndNumber = new Random(seed);
int randMachine = rndNumber.Next(0, max);
return randMachine;
}

如果我调用该方法两次,目前它会返回相同的随机数:

if I call the method two times, currently it's return me the same random number:

randM1 = SelectRandomMachine(maxNumber);
randM2 = SelectRandomMachine(maxNumber);

任何建议将不胜感激.

推荐答案

提示看这一行:

int seed = (int)DateTime.Now.Ticks;

如果您快速连续两次执行该行,您认为这些值会是多少?

If you execute that line twice in quick succession, what do you think the values will be?

例如:

int seed1 = (int)DateTime.Now.Ticks;
int seed2 = (int)DateTime.Now.Ticks;

// Write it out *after* executing; console output can take a while
Console.WriteLine(seed1);
Console.WriteLine(seed2);

有关解决方案和更多信息,请参阅我的关于随机性的文章.

See my article on randomness for solutions and more information.

这是缺乏线程安全导致问题的一个快速而肮脏的例子:

Here's a quick and dirty example of the lack of thread safety causing problems:

using System.Collections.Generic;
using System.Threading;

class Program
{
    const int Iterations = 1000000;
    static readonly Random rng = new Random();

    static void Main(string[] args)
    {
        List<Thread> threads = new List<Thread>();
        for (int i = 0;  i < 8; i++)
        {
            Thread t = new Thread(ExerciseRandom);
            threads.Add(t);
            t.Start();
        }
        foreach (Thread t in threads)
        {
            t.Join();
        }
        Console.WriteLine(rng.Next());
        Console.WriteLine(rng.Next());
        Console.WriteLine(rng.Next());
    }

    static void ExerciseRandom()
    {
        for (int i = 0; i < Iterations; i++)
        {
            rng.Next();
        }
    }
}

我的盒子上的输出:

0
0
0

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

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