Ich schreibe ein Programm, das einen Benutzer nach einem Schwierigkeitsgrad fragt und dann Multiplikationsfragen gibt, während er die richtigen Antworten zählt. Mein Problem ist mein Zähler() Updates für falsche Antworten und ich kann nicht verstehen warum. Kann mir jemand sagen warum?C++ - Zählervariable funktioniert nicht richtig
int main()
{
int n; //difficulty level
int a, b, atimesb; // random generated numbers and multiplication
string name;
int numCorrect=0; // initilize counter to 0
int numAsked=0; // initilize counter to 0
int exitCond = 1; // loop condition continue
cout << "this program tests your multiplication skills!" << endl;
cout << "what is your name?" << endl;
getline(cin, name);
cout << " Enter a difficulty level" << endl;
cin >> n; // user input for difficulty level
while (exitCond != 0) // loop to continue asking until user ends with 0
{
MakeQuestion(n, a, b, atimesb); // calls function to make a question
UserAnswerIsCorrect(a, b, atimesb); // calls function to ask question and evaluate it
if (UserAnswerIsCorrect) // update if correct
{
numCorrect++;
}
numAsked++; // update total questions
cout << " Enter 0 to quit, 1 to go again" << endl;
cin >> exitCond; // user input for difficulty level
}
PrintScore(numCorrect, numAsked); // calls function to print score
return 0;
}
int NewRandomNumber(int n)
{
int val;
val = rand() % n + 2; // creates a number between 2 and n
return val;
}
void MakeQuestion(int n, int& a, int& b, int& atimesb)
{
a = NewRandomNumber(n);
b = NewRandomNumber(n);
atimesb = a*b;
return;
}
bool UserAnswerIsCorrect(int a, int b, int atimesb)
{
int userAns;
cout << a << "X" << b << "=" << endl;
cin >> userAns;
if (userAns == atimesb)
{
cout << "Correct!";
return true;
}
else
{
cout << "false, correct answer is:" << atimesb << endl;
return false;
}
}
void PrintScore(int numCorrect, int numAsked)
{
cout << "your score is: " << numCorrect << "/" << numAsked << " or " <<
(numCorrect/numAsked) * 100 << "%" << endl;
return;
}
Um das Problem zu klären, wird 'UserAnswerIsCorrect' allein an der Adresse im Speicher dieser Funktion ausgewertet. Da das immer nicht Null ist, wertet die if-Anweisung es als wahr aus. – doug
Es scheint, dass dies nun dazu führt, dass die Schleife nach der ersten Antwort auf Laufzeitfehler stürzt. – Cole