这是我的代码的开头:
public partial class Form1 : Form
{
static Random random = new Random();
int prevnum;
int currentnum;
public int GenerateRandomNumber()
{
return random.Next(1, 1000);
}
public Form1()
{
int randomNumber = random.Next(1, 1000);
InitializeComponent();
}
private void enterButton_Click(object sender, EventArgs e)
{
currentnum = Convert.ToInt32(guessBox.Text);
if (randomNumber < currentnum)
{
warmOrColdLabel.Text = "Too High";
if (currentnum > prevnum)
{
guessBox.BackColor = Color.Blue;
prevnum = currentnum;
}
else
{
guessBox.BackColor = Color.Red;
prevnum = currentnum;
}
}
if (randomNumber > currentnum)
{
warmOrColdLabel.Text = "Too Low";
if (currentnum > prevnum)
{
guessBox.BackColor = Color.Blue;
prevnum = currentnum;
}
else
{
guessBox.BackColor = Color.Red;
prevnum = currentnum;
}
}
if (randomNumber == currentnum)
{
guessBox.Enabled = false;
enterButton.Enabled = false;
playAgainButton.Enabled = true;
}
}
private void playAgainButton_Click(object sender, EventArgs e)
{
enterButton.Enabled = true;
guessBox.Enabled = true;
playAgainButton.Enabled = false;
}
}
我遇到的问题是得到一个随机数,它总是输出0.我只需要一个随机数,我可以把它放到不同的按钮等等。我做错了什么?
编辑:必须是1到1000之间的随机数。
答案 0 :(得分:6)
您实际上并未在任何地方拨打RandomNumberHandler()
。此外,您需要在致电.Next()
时指定您的范围(例如,random.Next(1000)+1
以获取1到1000之间的数字。)
public partial class Form1 : Form
{
//other stuff from before
int randomNumber; //move this here
public Form1()
{
randomNumber = random.Next(1, 1000); //assign it here
InitializeComponent();
}
答案 1 :(得分:1)
主要问题是在调用构造函数时初始化randomNumber,此后当您访问它时,您将访问相同的值。
您应该删除该实例变量,而只是对GenerateRandom()进行新的调用。
此外,您可能希望将Random的实例设为静态变量:
static Random random =
否则,每次卸载并重新加载类时,它将重复相同的序列,该序列将不那么随机(或者更确切地说是伪随机)。