翻转硬币问题

| 我一直在玩,并编写了这段小代码。我试图翻转硬币定义的次数,然后计算我得到多少尾巴和头。所以这里是:
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();
    
已邀请:
代替
for (g = 0; g < input; g++)
{
   Random random = new Random();
   random2 = random.Next(2);
}
声明一个“ѭ3”以在整个过程中使用:
private Random randomGenerator = new Random();
private void Start_Click(object sender, EventArgs e)
{
    // ...
    for (g = 0; g < input; g++)
    {
        random2 = randomGenerator.Next(2);
    }
    // ...
}
    
您应该仅使用一个Random对象生成良好的(与默认Random一样好)随机序列。     
随机的默认构造函数将systmem时间作为种子。因此,如果您在短时间内生成大量随机数,它们都会生成相同的随机数序列。将随机对象拉出循环,这种效果将不会发生。     
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\");     
}
    

要回复问题请先登录注册