翻转硬币问题

时间:2011-04-25 05:42:28

标签: c# coin-flipping

我一直在玩,写下这段小代码。我试图翻转硬币定义的次数,然后计算我得到多少尾巴和头。所以这就是:

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);
}

问题是我在显示内容时一直遇到问题。它甚至没有显示出正确的结果。有什么想法吗?

EDIT。解决方案:沿着第3行向上移动:D

Random random = new Random();

4 个答案:

答案 0 :(得分:5)

而不是

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);
    }
    // ...
}

答案 1 :(得分:4)

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

答案 2 :(得分:2)

随机的默认构造函数将systmem时间作为种子。因此,如果您在很短的时间内生成大量的它们,它们将生成相同的随机数序列。将随机对象拉出循环,不会发生这种效果。

答案 3 :(得分: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");     
}