【问题标题】:How to keep count of right answer and wrong answers in C++?如何在 C++ 中计算正确答案和错误答案?
【发布时间】:2021-11-02 19:45:10
【问题描述】:

目前正在开发将循环直到用户输入“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;
}

【问题讨论】:

  • 为什么要在循环中创建新的rightwrong 变量?因此,您将在每次迭代中从 0 开始。还有,你为什么直接递增wrong
  • @mch 我是一个直接的初学者,我不知道该怎么做,当我意识到我在玩我的代码时离开了那些,我删除了这些
  • 尤其是初学者,从小处着手。编写一个小程序来做一件容易测试的事情。一旦它完全按照你想要的方式工作,再添加一件事。重复直到程序完成你需要它做的所有事情。这将您在任何时候必须处理的复杂性降至最低。
  • 如果您是初学者,您可能需要阅读a good book 的前几章,直到您熟悉计数等概念。这肯定比为你想尝试的每一个新事物写一个新问题要快。

标签: c++


【解决方案1】:

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

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返回之前,您可以打印统计信息。

【讨论】:

  • 我现在明白了这是如何工作的,以及为什么我的变量需要在开始时初始化。
猜你喜欢
  • 2015-04-14
  • 2020-04-01
  • 2017-05-21
  • 2021-04-24
  • 1970-01-01
  • 2012-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多