【问题标题】:C# random number generator still gives same number each time [duplicate]C#随机数生成器每次仍然给出相同的数字[重复]
【发布时间】:2013-11-03 22:07:52
【问题描述】:

// 创建一个由十行组成的字符串数组。 字符串 [] 个人号码; // 将个人号码声明为 10 元素数组 个人号码 = 新字符串 [10]; //= { "第一个数字"、"第二个数字"、"第三行"等}

        for (int i = 0; i < 9; i++)   // populate the array  with 10 random values
        {
            Random random = new Random();
            int randomNumber = random.Next(1, 50);

            string RandomNumberText = Convert.ToString(randomNumber);

            personalNumbers[i] = RandomNumberText;   
        }

您好,我知道这似乎与之前提出的问题重复,但我正在尝试 生成一系列介于 1 到 50 之间的随机数来填充数组

问题是,如果我按照我们在课堂上教的那样做,每个数字都是一样的

我知道问题在于紧密循环导致随机数以相同的数字播种

然而,其他线程没有解决的问题是如何在使用循环迭代时解决这个问题......

到目前为止,所有的解释都远远超出了我们的水平,以至于我(和其他提问者顺便说一句)不知道如何将它们作为解决方案实施,我也无法在课堂上提交,因为它们是我们拥有的技术未覆盖

微软的教程坚持认为将随机数放入循环中是正确的解决方案

我尝试将 random 的实例放在循环之外,然后从循环内部调用它,但这导致了异常

是否有一种直接的方法可以使用 random 来创建一系列不会遇到此问题的随机数?

【问题讨论】:

  • 如果您查看右侧的相关列,您可以找到答案。不,不要将随机放在循环内
  • 看起来是这样,random应该初始化一次..
  • “我尝试将 random 的实例放在循环之外,然后从循环内部调用它,但这导致了异常”。因此,您已尝试实施正确的解决方案,“它不起作用”。您能否与我们分享有关该异常的更多信息,或者向我们展示代码?因为听起来这实际上应该是解决方案:)
  • “微软的教程坚持认为将随机放入循环是正确的解决方案”什么教程?

标签: c# random


【解决方案1】:

我尝试将 random 的实例放在循环之外,然后 从循环内部调用它,但这导致了异常

这里有两个具体示例,一个用于控制台应用程序,另一个用于 WinForms 应用程序。

这是在控制台应用程序中声明它的一种方式。 random 可以在应用程序的任何地方使用,即使在 Main() 以外的方法中:

class Program
{

    private static Random random = new Random();

    static void Main(string[] args)
    {
        // ... code ...

        for (int i = 0; i < 9; i++)   // populate the array  with 10 random values
        {
            int randomNumber = random.Next(1, 50);

            personalNumbers[i] = randomNumber.ToString();
        }

        // ... code ...
    }

}

这是声明它以在 WinForms 应用程序中使用的一种方式。 random 在这个例子中可以在 Form1 中的任何地方使用:

public partial class Form1 : Form
{

    private Random random = new Random();

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // ... code ...

        for (int i = 0; i < 9; i++)   // populate the array  with 10 random values
        {
            int randomNumber = random.Next(1, 50);

            personalNumbers[i] = randomNumber.ToString();
        }

        // ... code ...
    }

}

这应该涵盖最简单的家庭作业。这里没什么特别的。

【讨论】:

  • 谢谢 Idle_Mind... 这比我希望的要简单和优雅得多...我害怕这样做,因为似乎使用 random.Next(1, 50) 会生成相同的重复数字我是否正确理解随机的外部实例是实际生成随机数和随机数的部分。循环内的下一个只是获取该值(或调用它,我想)?
  • 没错!...你明白了。
【解决方案2】:

在循环外创建随机实例:

Random random = new Random();
for (int i = 0; i < 9; i++)   // populate the array  with 10 random values
{

MSDN:

随机数生成从种子值开始。如果一样 种子重复使用,生成相同的数字序列。一 产生不同序列的方法是使种子值 时间相关,从而产生不同的系列与每个新的 随机的实例。默认情况下,的无参数构造函数 Random 类使用系统时钟生成其种子值,而 它的参数化构造函数可以采用一个 Int32 值,基于 当前时间的刻度数。然而,由于时钟有 有限分辨率,使用无参数构造函数创建 不同的随机对象连续创建随机数 产生相同随机数序列的生成器。

【讨论】:

    【解决方案3】:

    您必须在循环外定义Random 对象,并且每次在循环内获取一个数字。如果你每次都创建它,因为创建的间隔太小,它会被创建为相同的初始值。

    Random random = new Random();
    
    for (int i = 0; i < 9; i++) {
     int randomNumber = random.Next(1, 50);
    } 
    

    【讨论】:

      【解决方案4】:

      感谢您的意见,非常感谢!

      到目前为止,我已经发布了完整的代码,现在它给了我看起来像“随机”的数字 因为当我运行它时它们总是不同的

      @Steve 谢谢...我已经查看了这些问题,但所有解决方案都涉及使用我不允许使用的 random() 以外的其他技术

      @Oerkelens 谢谢,当我将 random() 的代码移到循环之外时,我得到了两个可能的结果 一个是一系列 9、9 位的随机数,或者是一个例外

      错误 1 ​​无法在此范围内声明名为“randomNumber”的局部变量,因为 它会给'randomNumber'赋予不同的含义,它已经在'父或当前'范围中用于表示其他东西

      我已经发布了更大的代码以显示我为使其工作所做的更改...我真的不明白如何从循环中正确调用 random(),但出于某种原因,有循环内部和外部的同一行就可以了

      @Preston - 我们没有本课程的教科书,我们只能使用 Bob Tabor (learnvisualstudiodotnet) 和 Envato (30 天内学​​习 C#) 的 Microsoft C# 视频教程中包含的技术

      如果这一切对您来说似乎很明显,我深表歉意,但是在课程进行到一半时,我们被告知我们正在从学习 Visual Basic 编程切换到 C#,所以我们所有的工作现在都需要用 C# 重新编写,没有任何关于如何使用这种语言的特别说明......不用说,这是一个巨大的压力,我们没有任何资源来做这件事,我们现在的很多事情做的只是猜测

      “工作”的更完整的代码

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.IO;
      
      namespace GuessingGameProgram
      {
      class Program
      {
          int randNum;
          static void Main(string[] args)
          {
              // Create a string array that consists of ten lines. 
              string[] personalNumbers; // declare personalNumbers as a 10-element array 
              personalNumbers = new string[10];  //= { "First number", "Second number", "Third line",   etc}
      
              Random outsideLoopRandom = new Random();
              int randomNumber = outsideLoopRandom.Next(1, 50);
      
      
              for (int i = 0; i < 9; i++)   // populate the array  with 10 random values
              {
                  randomNumber = outsideLoopRandom.Next(1, 50);
                  string RandomNumberText = Convert.ToString(randomNumber);
      
                  personalNumbers[i] = RandomNumberText;   
              }
      
              // WriteAllLines creates a file, writes a collection of strings to the file, 
              // and then closes the file.
              //System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);
      
      
      
              foreach (string i in personalNumbers) // this is just a test to see what the output is
              {
                  Console.Write("{0} ", i);
              }
      
      
              Console.ReadLine();
      
      
      
          }
      }
      

      }

              //randNum = Random.Equals(1, 50);
      
      
      
              //StreamReader myReader = new StreamReader("personalNumbers.txt");
              //string line = "";
              //while (line != null)
              //{
              //    line = myReader.ReadLine();
              //    if (line != null)
              //        Console.WriteLine(line);
              //}
      
              //myReader.Close();
              //Console.ReadLine();
      
              //personalNumbers = RandomNumbers.next(1, 10);
      
              //int returnValue = personalNumbers.Next(1, 50);
      
              //int Guess = 0;
      
              //Console.WriteLine("Please guess a number between 1 and 50");
              //Console.ReadLine();
              ////while (Guess = Convert.ToInt32(Console.Read());
      
              //if (Guess < returnValue)
              //{
              //    Console.WriteLine("Wrong! the number that I am thinking of is higher than " + Guess + ". Try again!");
              //    Console.ReadLine();
              //}
      
              //if (Guess > returnValue)
              //{
              //    Console.WriteLine("Wrong! The number that I am thinking of is lower than " + Guess + ". Try again!");
              //    Console.ReadLine();
              //}
              //        else if (Guess = returnValue)
              //        Console.WriteLine("Correct! The number that I was thinking of was " + Guess + ". Congratulations!");
          //    //{
          //Console.WriteLine("Let's play a guessing game!")
          //Console.WriteLine("")
          //Console.WriteLine("guess a number between 1 and 10")
          //Console.WriteLine("")
      
      
      
          //randNum = randomGenerator.Next(1, 10)
      
      
          //While userGuess <> randNum
          //    {
      
          //    userGuess = Console.ReadLine()
          //    }
          //    If userGuess > randNum Then
          //        Console.WriteLine("too high, guess again!")
          //    {
          //   If userGuess < randNum Then
          //        Console.WriteLine("too low, guess again!")
          //    }
          //   Else
      
      
          //End While
      
          //Console.WriteLine("Correct! the secret number is " & randNum)
          //Console.ReadLine()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-10
        • 2021-03-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-06
        • 1970-01-01
        • 1970-01-01
        • 2014-05-07
        相关资源
        最近更新 更多