我一直在玩耍,寫下這段小小的代碼。我試圖翻轉定義次數的硬幣,然後計算我得到的尾數和頭數。所以這裏是:翻轉硬幣問題
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();
顯示器看起來不錯,但翻轉並不好。 「隨機」的默認種子基於系統時鐘,其分辨率不是很好。通過在循環中每次創建一個新的'Random'對象,您將在許多迭代中反覆得到相同的種子,因此您的翻轉將不會非常隨意。 – mquander 2011-04-25 05:47:41