2017-03-19 8 views
1

ユーザーに難易度を尋ねるプログラムを書いていて、正しい答えを数えながら乗算の質問を出しています。私の問題は私のカウンター(numCorrect)も誤った答えの更新であり、私はなぜそれを理解できません。誰かが私に理由を教えてくれますか?C++カウンター変数が正しく機能していない

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; 
} 

答えて

1
UserAnswerIsCorrect(a, b, atimesb); // calls function to ask question and evaluate it 

    if (UserAnswerIsCorrect) // update if correct 
    { 
     numCorrect++; 
    } 

あなたは、あなたのコード内でUserAnswerIsCorrectの戻り値を無視

if (UserAnswerIsCorrect(a, b, atimesb)) // update if correct 
    { 
     numCorrect++; 
    } 

でなければなりません。

+0

問題を明確にするために、 'UserAnswerIsCorrect'だけで、その関数のメモリ内のアドレスを評価します。それは常にゼロではないので、if文はそれを真と評価します。 – doug

+0

これは、プログラムがランタイムエラーに最初に応答した後にループが失敗するように見える – Cole

-1

を使用すると、戻り値を無視したために、それはちょうど起こったが、あなたはこの

bool corr; 
corr = UserAnswerIsCorrect(a, b, atimesb); 
if(corr) { 
numCorrect++; 
} 

を行うことができます

if(UserAnswerIsCorrect == true){ 
    .... 
} 
+1

このコードは質問に答えるかもしれませんが、問題の解決方法および/または原因を解説する理由を追加すると、 。 –

+0

私はこれがUserAnserIsCorrectがブール値であると信じていません。 – Cole

+0

関数呼び出しの構文が無効です。また、説明がない場合は答えではありません。 –

0

この条件を試してみてください。

関連する問題