生成随机数

时间:2016-09-17 08:38:00

标签: c# .net

我正在尝试根据用户输入生成随机数。因此,如果用户输入10,那么我想生成10个随机数。我从文本框中获取用户输入。

   private void GenerateRandomNumber()
            {

                int count = 1;

                //Int32.TryParse(GeneratetextBox.Text, out UserNumber);
                UserNumber = Convert.ToInt32(GeneratetextBox.Text);

                ///creates random object to produce random values 
                Random randomNumbers = new Random();

                while (count == UserNumber)
                {
                    //UserNumber = randomNumbers.Next(100);

                    listBox.Items.Add(randomNumbers.Next(100));

                    count = count + 1;
                }

                //for ( count = UserNumber; count == UserNumber; count++)
                //{
                //    UserNumber = randomNumbers.Next(100);

                //    listBox.Items.Add(randomNumbers.Next(100));

                //    count = count + 1;
                //}
    }

2 个答案:

答案 0 :(得分:2)

尝试这样来生成随机数:

        private void GenerateRandomNumber()
        {                
            int userNumber= Convert.ToInt32(GeneratetextBox.Text);

            Random randomNumbers = new Random();

             // loop until i is not les than userNumber

            for (int i = 0; i < userNumber; i++){  
                  // generate random number and add it to the list.
                  int randNumber= randomNumbers.Next(100);
                  listBox.Items.Add(randNumber);
            }
          }

          private void button1_Click(object sender, EventArgs e)
          {
             // clear listbox before generating new numbers
             listBox.Items.Clear();
             GenerateRandomNumber();
           }

如果您使用按钮触发此方法,请不要忘记在生成新的randnubers之前清除列表框。

答案 1 :(得分:1)

当count与UserNumber不同时,while循环停止,因此,如果你想要执行while中的代码,那么当你初始化count = 1时,你需要让UserNumber = 1。

所以,你需要修复while条件:

private void GenerateRandomNumber()             {

            int count = 1;

            //Int32.TryParse(GeneratetextBox.Text, out UserNumber);
            UserNumber = Convert.ToInt32(GeneratetextBox.Text);

            ///creates random object to produce random values 
            Random randomNumbers = new Random();

            while (count <= UserNumber)
            {
                //UserNumber = randomNumbers.Next(100);

                listBox.Items.Add(randomNumbers.Next(100));

                count = count + 1;
            }

            //for ( count = UserNumber; count == UserNumber; count++)
            //{
            //    UserNumber = randomNumbers.Next(100);

            //    listBox.Items.Add(randomNumbers.Next(100));

            //    count = count + 1;
            //}
}

这样,当UserNumber大于count时,while内的代码将停止执​​行,这正是您要查找的内容。