随机数生成:如果我运行,则在C#中返回相同的数字。好的,如果逐步调试

问题描述 投票:5回答:8

我在使用C#生成随机数时遇到问题。如果我直接RUN此表单应用程序,则所有的随机数生成都是相同的。

如果我通过按F10一行一行地DEBUG,则它将生成不同的随机数。为什么会这样呢?如何生成不同的随机数?

Greyhound.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ADayAtTheRaces
{
    class Greyhound
    {
        int location=0;
        Random randomize = new Random();

        public int run()
        {
            location = randomize.Next(0, 100);
            return location;
        }
    }
}

Form1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ADayAtTheRaces
{
    public partial class Form1 : Form
    {
        Greyhound[] greyHound = new Greyhound[4];
        ProgressBar[] progressBar = new ProgressBar[4];
        public Form1()
        {
            InitializeComponent();
            for (int i = 0; i < 4; i++)
            {
                greyHound[i] = new Greyhound();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i <= 3; i++)
            {
                progressBar[i].Value = greyHound[i].run();
            }
        }
    }
}
c#
8个回答
10
投票

不要每次都实例化一个新的Random对象,而是将其用作static成员:


3
投票

您正在同时创建x数量的新随机数。


2
投票

您的答案在这里:Random Constructor


1
投票

戴维德说得很对。实际上,这就是修复代码的方式。


1
投票

尝试使随机化为静态。我猜问题出在种子是时间依赖的事实。


1
投票

之所以获得相同的随机数,是因为您正在为每个实例创建一个Random对象。随机生成器是从时钟开始播种的,因此当您创建时间太近的随机对象时,它们最终都将具有相同的种子,并产生相同的随机数。


1
投票

每次实例化GreyHound的实例时,都实例化System.Random的实例。 System.Random的默认构造函数使用System.Environment.TickCount 作为生成随机数的种子。 System.Environment.TickCount的分辨率为毫秒,因此您创建实例的速度要快得多。也许使System.Random实例正在使用static ...将可以解决问题。


0
投票

之所以发生这种情况,是因为调试花费的时间很少,而且可以随机更改。滥用它,对我有帮助

© www.soinside.com 2019 - 2024. All rights reserved.