-3

我写了一个简单的代码,我想防止重复的随机数。

最简单的方法是什么?

 Random rnd = new Random();

        int n1, n2, n3, n4, n5, n6, n7;

        n1 = rnd.Next(1, 37);
        n2 = rnd.Next(1, 37);
        n3 = rnd.Next(1, 37);
        n4 = rnd.Next(1, 37);
        n5 = rnd.Next(1, 37);
        n6 = rnd.Next(1, 37);
        n7 = rnd.Next(1, 7);

        Console.WriteLine("1 Number ({0})", n1);
        Console.WriteLine("2 Number ({0})", n2);
        Console.WriteLine("3 Number ({0})", n3);
        Console.WriteLine("4 Number ({0})", n4);
        Console.WriteLine("5 Number ({0})", n5);
        Console.WriteLine("6 Number ({0})", n6);
        Console.WriteLine("Additionl Number ({0})", n7);
    }
}

}

4

1 回答 1

-1

我有同样的问题。改用这个:

private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public int RandomNumber(int min, int max)
{
    lock (syncLock)
    { // synchronize
        return random.Next(min, max);
    }
}

用法

int randomNumber = RandomNumber(0, 10); // random number between 0 and 10
于 2013-06-09T15:39:01.157 回答