首页 > 解决方案 > 如何在 C++ 中计算正确答案和错误答案?

问题描述

目前正在开发将循环直到用户输入“n”的添加程序。

它将生成两个随机数并显示给用户以添加它们。然后用户将输入答案和程序,并检查答案是对还是错。

我的代码运行良好,但是我需要以下代码的帮助来计算正确和错误的答案。

我什么都不累,因为我不知道该怎么做。

/******************************************************************************
Basic Template for our C++ Programs.
STRING
*******************************************************************************/
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <string> // String managment funtions.
#include <iostream> // For input and output
#include <cmath> // For math functions.
#include <math.h>
#include <cstdlib>
using namespace std;
////////////////////////////////////////////////////////////////////////

int main()
{
    srand(time(0));

    string keepgoing;
    do
    {
        const int minValue = 10;
        const int maxValue = 20;

        int y = (rand() % (maxValue - minValue + 1)) + minValue;
        // cout<< " the random number is y "<< y << endl;
        int x = (rand() % (maxValue - minValue + 1)) + minValue;
        // cout<< " the random number is x "<< x << endl;


        cout << " what is the sum of " << x << " + " << y << " =" << endl;
        int answer;
        cin >> answer;

        


        if (answer == (x + y))
        {
            cout << "Great!! You are really smart!!" << endl;
           
        }

        else
        {
            cout << "You need to review your basic concepts of addition" << endl;
          
        }
       

        cout << "Do you want to try agian [enter y (yes) or n (no) ]";
        cin >> keepgoing;

    } while (keepgoing == "y");
    return 0;
}

标签: c++

解决方案


为了让生活更轻松,让我们使用两个变量:

unsigned int quantity_wrong_answers = 0U;
unsigned int quantity_correct_answers = 0U;

(这应该在do声明之前。)

当您检测到正确答案时,请增加以下变量之一:

if (answer = (x+y))
{
    ++quantity_correct_answers;
}
else
{
    ++quantity_wrong_answers;
}

在返回之前main,您可以打印统计信息。


推荐阅读