如何在 asp.net 网络表单中生成 5 个不同的随机数
How to generate 5 different random number in asp.net webforms
如何通过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() 放入循环中,如下例所示:
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);
然后根据需要在数组或字符串或不同的文本框中使用它。
您可以将每个生成的数字添加到列表中。然后检查是否包含。
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();
带有随机化器初始化的简短示例
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();
}
如何通过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() 放入循环中,如下例所示:
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);
然后根据需要在数组或字符串或不同的文本框中使用它。
您可以将每个生成的数字添加到列表中。然后检查是否包含。
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();
带有随机化器初始化的简短示例
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();
}