You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C++加法答题程序中如何统计正确与错误答案的数量?

加法练习程序计数功能实现方案

修改步骤

  • 在do-while循环体外部定义两个整型计数变量:correct统计答对题数,wrong统计答错题数,初始值均设为0
  • 答对判断分支中对正确计数变量执行自增操作,答错判断分支中对错误计数变量执行自增操作
  • 循环结束(用户选择退出)后,打印最终的答题统计结果,可选补充计算正确率展示

修改后完整代码

/******************************************************************************
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));
    // 新增计数变量
    int correct = 0;
    int wrong = 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;
            correct++; // 答对计数+1
        }
        else
        {
            cout << "You need to review your basic concepts of addition" << endl;
            wrong++; // 答错计数+1
        }
       
        cout << "Do you want to try again [enter y (yes) or n (no) ]";
        cin >> keepgoing;

    } while (keepgoing == "y");
    // 退出程序前打印统计结果
    cout << endl << "本次练习统计:" << endl;
    cout << "答对:" << correct << " 题" << endl;
    cout << "答错:" << wrong << " 题" << endl;
    if(correct + wrong > 0) {
        cout << "正确率:" << (correct * 100.0) / (correct + wrong) << "%" << endl;
    }
    return 0;
}

内容的提问来源于stack exchange,提问作者user17312577

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 17:06:03