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

问题描述

可能的重复:
随机数生成器只生成一个随机数

初学者问题.我有一个非常简单的画线程序,我想随机化位置,但是每次我创建一个新的 Random 实例时,它都会返回相同的值.哪里有问题?谢谢.

A beginner question. I have a very simple program that draws a line and I want to randomize the locations, but each time I create a new instance of Random it returns the same value. Where is the problem? Thank you.

private void Draw()
{
    Random random1 = new Random();
    int randomNumber1 = random1.Next(0, 300);
    Random random2 = new Random();
    int randomNumber2 = random2.Next(0, 300);
    Random random3 = new Random();
    int randomNumber3 = random3.Next(0, 300);
    Random random4 = new Random();
    int randomNumber4 = random4.Next(0, 300);
    System.Drawing.Graphics g = this.CreateGraphics();
    Pen green = new Pen(Color.Green, 5);
    g.DrawLine(green, new Point(randomNumber1, randomNumber2),
                      new Point(randomNumber3, randomNumber4));
}

private void btndraw1_Click(object sender, EventArgs e)
{
    Draw();
}

推荐答案

发生这种情况的原因是每次你做一个新的 Random 时,它都会使用时钟进行初始化.所以在一个紧密的循环中(或者一个接一个的多次调用)你会多次得到相同的值,因为所有这些随机变量都是用相同的种子初始化的.

The reason this happens is that every time you do a new Random it is initialized using the clock. So in a tight loop (or many calls one after the other) you get the same value lots of times since all those random variables are initialized with the same seed.

要解决这个问题:只创建一个随机变量,最好在你的函数之外,并且只使用那个实例.

To solve this: Create only one Random variable, preferably outside your function and use only that one instance.

Random random1 = new Random();
private void Draw()
{
    int randomNumber1 = random1.Next(0, 300);
    int randomNumber2 = random1.Next(0, 300);
    int randomNumber3 = random1.Next(0, 300);
    int randomNumber4 = random1.Next(0, 300);
    System.Drawing.Graphics g = this.CreateGraphics();
    Pen green = new Pen(Color.Green, 5);
    g.DrawLine(green, new Point(randomNumber1, randomNumber2), new Point(randomNumber3, randomNumber4));
}

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

08-23 16:21