3

我一直在玩耍并编写了这段小代码。我正在尝试将硬币翻转定义的次数,然后计算我得到了多少个反面和正面。所以这里是:

private void Start_Click(object sender, EventArgs e)
{
    int headss = 0;
    int tailss = 0;
    int random2, g;
    string i = textBox1.Text;
    int input2, input;
    bool NumberCheck = int.TryParse(i, out input2);

    if (textBox1.Text == String.Empty) // check for empty string, when true
        MessageBox.Show("Enter a valid number between 0 and 100000.");
    else // check for empty string, when false
        if (!NumberCheck) // number check, when false
        {
            textBox1.Text = String.Empty;
            MessageBox.Show("Enter a valid number between 0 and 100000.");
        }
        else
        {
            input = Convert.ToInt32(textBox1.Text);

            for (g = 0; g < input; g++)
            {
                Random random = new Random();
                random2 = random.Next(2);

                if (random2 == 0)
                {
                    headss++;
                }
                else if (random2 == 1)
                {
                    tailss++;
                }
            }
        }

    heads.Text = Convert.ToString(headss);
    tails.Text = Convert.ToString(tailss);
}

问题是我在显示内容时不断遇到问题。显示他们正确的结果甚至还差得远。有任何想法吗?

编辑。解决方案:将以下第 3 行向上移动:D

Random random = new Random();
4

4 回答 4

7

代替

for (g = 0; g < input; g++)
{
   Random random = new Random();
   random2 = random.Next(2);
}

声明一个Random供整个使用:

private Random randomGenerator = new Random();
private void Start_Click(object sender, EventArgs e)
{
    // ...
    for (g = 0; g < input; g++)
    {
        random2 = randomGenerator.Next(2);
    }
    // ...
}
于 2011-04-25T05:49:30.370 回答
4

您应该只使用一个 Random 对象来生成好的(与默认的 Random 一样好)随机序列。

于 2011-04-25T05:46:13.833 回答
3

random 的默认构造函数将系统时间作为种子。因此,如果您在短时间内生成大量它们,它们都会生成相同的随机数序列。将随机物体拉出循环,不会出现这种效果。

于 2011-04-25T05:48:42.333 回答
0

RandomGenerator. 此代码将计算掷硬币的次数。它将以连续 3 个 HEADS 结束。

private RandomGenerator rgen = new RandomGenerator ();

public void run () {

    int value = 0;
    int total = 0;
    while (value != 3) {
        String coinFlip =  rgen.nextBoolean() ? "HEADS" : "TAILS";
        println (coinFlip);
        if (coinFlip == "HEADS") {
           value+=1;
        } else {
           value=0;
        }
        total +=1;
    }
    println ("It took "+total+" flips to get 3 consecutive heads");     
}
于 2018-01-20T19:36:40.133 回答