我的程序設置爲讓用戶猜測1到10之間的一個整數。如果用戶猜測得太低或者太高,他們會收到通知並可以重試。在c中保留一個隨機數#
我遇到的問題是,當用戶猜測錯誤地產生一個新的隨機數。所以基本上,用戶在錯誤發生後從未嘗試過猜測相同的號碼。
我需要這樣做,以便當用戶猜錯時他們仍然試圖猜測相同的值。
這是我的代碼:
namespace IntegerGame
{
public partial class guessGame : Form
{
int num1;
int num2;
public guessGame()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void guessButton_Click(object sender, EventArgs e)
{
Random rnd1 = new Random();
num1 = rnd1.Next(1, 10);
if (int.TryParse(textBox1.Text, out num2))
{
if (num2 < 0 || num2 > 10)
{
textBox1.Clear();
MessageBox.Show("Please enter a number between 1 and 10");
}
else
{
if (num2 > num1)
{
textBox1.Clear();
MessageBox.Show("You guessed to high, please try again");
}
else if (num2 < num1)
{
textBox1.Clear();
MessageBox.Show("You guessed to low, please try again");
}
else if (num2 == num1)
{
textBox1.Clear();
MessageBox.Show("You guessed " + num2 + ", which was the right number!!");
}
}
}
else
{
textBox1.Clear();
MessageBox.Show("This is not a valid integer, please enter a valid integer");
}
}
}
}
提示:將您的一代移至其他方法。 –
另一個提示與第一個一起:將'Random rnd1'移動到與'var num1'相同的地方 –
您希望程序如何工作?像什麼時候應該生成一個新號碼?或者每次運行只有一次? – Michael