C# 程序说无论输入如何,答案都是正确的
本文关键字:答案 程序 输入 | 更新日期: 2023-09-27 18:36:51
程序总是说你输入的任何数字的答案都是正确的。当您键入字符时,它会将其输出为不正确。我不确定它为什么要这样做。我是 C# 的新手,所以放轻松!
// Create a Random object to generate random numbers.
Random randomizer = new Random();
// for the addition problem.
int num1;
int num2;
int sum;
int correct;
int incorrect;
private void play_Load(object sender, EventArgs e)
{
StartTheGame();
}
public void StartTheGame()
{
num1 = randomizer.Next(11);
num2 = randomizer.Next(11);
sum = num1 + num2;
labelNum1.Text = num1.ToString();
labelNum2.Text = num2.ToString();
}
private void labelNum1_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
}
private void btnSub_Click(object sender, EventArgs e)
{
if (int.TryParse(txtUserAnswer.Text, out sum))
{
MessageBox.Show("Correct Answer!", "Correct");
correct++;
}
else
{
MessageBox.Show("You messed up.", "Incorrect");
incorrect++;
}
txtUserAnswer.Clear();
txtUserAnswer.Focus();
StartTheGame();
if(correct == 5)
{
MessageBox.Show("Congrats! You defeated the monster.", "Next Level");
}
if(incorrect == 3)
{
MessageBox.Show("You've been defeated. Nerd.", "Loser");
Application.Exit();
}
}
请帮帮我!这是为了上学,这让我很困扰!
你在这里所做的只是尝试解析。只要int.TryParse(txtUserAnswer.Text, out sum)
的输入是整数,这个条件总是true
。
txtUserAnswer.Text = "1235"; //this result in true
txtUserAnswer.Text = "44"; //this result in true
txtUserAnswer.Text = "999999"; //this result in true
txtUserAnswer.Text = "123bbn"; //this result in false
您必须使用与 sum
不同的变量名添加检查条件。否则,您的sum
将被用户的输入替换:
int guesssum; //declare this
.
.
if (int.TryParse(txtUserAnswer.Text, out guesssum)) //use guesssum here
{
if (guesssum == sum){
MessageBox.Show("Correct Answer!", "Correct");
correct++;
}
else {
//wrong, do something!
}
}