以下是名为“Addition Tutor”的程序的代码。该程序生成2个随机数,并请求用户回答两个随机数的加法。问题是每次我正确回答问题时,消息框都会返回else动作(“不正确”)。我的程序有什么问题?请保持答案简单,我的编程知识和术语非常有限。非常感谢您的帮助!
namespace Addition_Tutor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//Create a random object.
Random rand = new Random();
{
//Declare an Integer
int number1;
//Generate a random integer and assign it to number1
number1 = rand.Next(400) + 100;
//Send random number to numberlabel1
numberLabel1.Text = Convert.ToString(number1);
}
{
//Declare an Int Variable
int number2;
//Generate a random integer and assign it to number2
number2 = rand.Next(400) + 100;
//Send random number to numberlabel2
numberLabel2.Text = Convert.ToString(number2);
}
}
private void checkButton_Click(object sender, EventArgs e)
{
//declare an Int Variable for Correct Answer
int correctAnswer;
correctAnswer = Convert.ToInt32("" + numberLabel1.Text + numberLabel2.Text);
//check to see if the userAnswer and correctAnswer match.
int userAnswer;
userAnswer = Convert.ToInt32(answerTextBox.Text);
if (userAnswer == correctAnswer)
{
MessageBox.Show("Your Answer is Correct");
}
else
{
MessageBox.Show("Your Answer is Incorrect");
}
}
private void clearButton_Click(object sender, EventArgs e)
{
//clear the labels and textboxes.
numberLabel1.Text = "";
numberLabel2.Text = "";
answerTextBox.Text = "";
}
private void exitButton_Click(object sender, EventArgs e)
{
//close the form
this.Close();
}
}
}
答案 0 :(得分:0)
correctAnswer = Convert.ToInt32("" + numberLabel1.Text + numberLabel2.Text);
你正在“连接”两个数字。与"1" + "2" = "12"
一样。
在添加之前,您需要将它们解析为int
:
correctAnswer = int.Parse(numberLabel1.Text) + int.Parse(numberLabel2.Text);