C ++计数器变量无法正常工作

时间:2017-03-19 03:34:49

标签: c++

我正在编写一个程序,要求用户提供难度级别,然后在计算正确答案时给出乘法问题。我的问题是我的计数器(numCorrect)更新了错误的答案,我无法理解为什么。有人可以告诉我为什么吗?

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

3 个答案:

答案 0 :(得分:1)

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

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

应该是

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

您忽略了代码中UserAnswerIsCorrect的返回值。

答案 1 :(得分:0)

你可以这样做

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

虽然它刚刚发生,因为你忽略了返回值。

答案 2 :(得分:-1)

试试这个条件

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