多个随机数相同

编程入门 行业动态 更新时间:2024-10-27 01:26:01
本文介绍了多个随机数相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

初学者问题.我有一个非常简单的画线程序,我想随机化位置,但是每次我创建一个新的 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)); }

更多推荐

多个随机数相同

本文发布于:2023-11-08 08:06:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568820.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数   多个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!