如何生成 5 个不同的随机数并且必须至少包含 1 个负数(asp.net 网络表单)

How to generate 5 different random number and must include at least 1 negative number (asp.net webforms)

我想在文本框中生成5个随机数,至少包括1个负数

您可以简单地选择一个随机负数,然后将其分配给一个随机文本框,然后使用您的代码填充其他文本框:

private Random rand = new Random();

protected void Button1_Click(object sender, EventArgs e)
{
    var textBoxes = new List<TextBox> { TextBox1, TextBox2, TextBox3, TextBox4, TextBox5 };

    // Pick a random negative number and assign it to a random textbox
    var negNumber = rand.Next(-100, 0).ToString();
    var randomTextboxIndex = rand.Next(textBoxes.Count);
    textBoxes[randomTextboxIndex].Text = negNumber;

    // Assign the other textboxes random numbers
    for (int i = 0; i < textBoxes.Count; i++)
    {
        if (i == randomTextboxIndex) continue;
        textBoxes[i].Text = rand.Next(-100, 101).ToString();
    }
}

这类似于 Rufus 的代码,但更加简洁:

private Random rand = new Random();

protected void Button1_Click(object sender, EventArgs e)
{
    var textBoxes = new [] { TextBox1, TextBox2, TextBox3, TextBox4, TextBox5 };

    // Pick a random textbox that shall be negative
    var negTb = rand.Next(textBoxes.Length);
    
    for (int i = 0; i < textBoxes.Length; i++)
        textBoxes[i].Text = rand.Next(-100, i == negTb ? 0 : 101).ToString();
    
}

随机决定哪个 tb 应为负,然后在分配时,将该索引 tb 的随机上限设置为 0 而不是 101