So when the user inputs the answer to the text box it will increment and display a score in the top right. But for some reason the program executes the if statement even though the user's inputted answer is incorrect. It will also only execute the if statement on the first go. Here is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int firstNum = rand()%100 + 1;
int secondNum = rand()%100 + 1;
int answer = System::Convert::ToInt32(textBox1->Text);
int correct = firstNum + secondNum;
float score;
this->textBox1->Clear();
this->num1->Text = System::Convert::ToString(firstNum);
this->num2->Text = System::Convert::ToString(secondNum);
if (answer = correct){
++score;
}
this->numScore->Text = System::Convert::ToString(score);
int answer;
int correct;
int num1;
int num2;
num1 = rand()%100 + 1;
num2 = rand()%100 + 1;
correct = num1+num2;
cout << "What is " << num1 << "+ " << num2 << endl;
cin >> answer;
if (answer = correct) {
cout << "Correct" << endl;
}
else {
cout << "Incorrect" << endl;
}
return 0;
}
But for some reason the code ignores the if statement and executes it's content (cout Correct) no matter what. So say if I answer that 1+1 is 5 it will still tell me it's correct.
Look closely at line 13, the compiler should give you a warning. That code does not do what you want (does not check for equality), it assign "correct" value to "answer" variable instead (and that of course always evaluates to be true).
The fix is to use "==" operator.