【问题标题】:How to generate 5 different random number in asp.net webforms如何在asp.net webforms中生成5个不同的随机数
【发布时间】:2021-02-21 16:32:50
【问题描述】:

如何通过1个按钮在文本框中生成5个不同的随机数?

protected void Button1_Click(object sender, EventArgs e)
        {
            Random r = new Random();
            int num = r.Next();      
            TextBox1.Text = num.ToString();
            TextBox2.Text = num.ToString();
            TextBox3.Text = num.ToString();
            TextBox4.Text = num.ToString();
            TextBox5.Text = num.ToString();
        }

我知道这样只会得到相同的数字,但是有什么办法可以得到不同的数字吗?

【问题讨论】:

  • 重复r.Next()?

标签: c# asp.net webforms


【解决方案1】:

随机化初始化的简短示例

    static void Example()
    {
          var textBoxes = new List<TextBox> { Textbox1, Textbox2, Textbox3, Textbox4, Textbox5 };
          // GUID will produce better randomization
          var rand = new Random(Guid.NewGuid().GetHashCode());        
          foreach (var textBox in textBoxes)
                textBox.Text = rand.Next().ToString();
     }

【讨论】:

    【解决方案2】:

    你可以像下面的例子一样把 r.Next() 放在循环中:

        string printmsg = string.Empty;
        int[] x = new int[5];
        Random r = new Random();
        for (int i = 0; i < 5; i++)
        {
            x[i] = r.Next();
            printmsg += x[i] + ",";
        }
        lblMsg.Text = printmsg.Substring(0, printmsg.Length-1);
    

    然后根据需要在数组或字符串或不同的文本框中使用它。

    【讨论】:

      【解决方案3】:

      您可以将每个生成的数字添加到列表中。然后检查是否包含。

                          Random r = new Random();
                          var list = new List<int>(5);
                          for (int i = 0; i < 5; i++)
                          {
                              var num = r.Next(5);
                              if (!list.Contains(num)) //If not add to list 
                              {
                                  list.Add(num);
                              }
                              else //If contains return back and generate again.
                              {
                                  i--; 
                              }
                          }
                        //It will more effective if you convert this section into loop. 
                          Textbox1.Text = list[0].ToString();
                          Textbox2.Text = list[1].ToString();
                          Textbox3.Text = list[2].ToString();
                          Textbox4.Text = list[3].ToString();
                          Textbox5.Text = list[4].ToString();
      

      【讨论】:

        猜你喜欢
        • 2014-10-14
        • 1970-01-01
        • 2014-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多