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

C++新手求助:如何用数组实现计算器计算历史存储功能?

如何用数组存储C++计算器的计算记录?

我是编程社区的新手,想在自己的C++计算器里存储已完成的计算记录,希望用数组实现,但不知道怎么把这个功能加到现有代码里。以下是我的代码:

#include<iostream>
#include<stdlib.h>

using namespace std;

int calculator();
void history();
void choice();

int main()
{
    int x;
    cout << "\t\t\t\tWhat do you want to do?\n\n";
    cout << "\t\t\t\t[1] Standard calculator\n";
    cout << "\t\t\t\t[2] History\n";
    cout << "\t\t\t\t[3] Exit\n\n\n\n";
    cout << "\t\t\t\tChoice: ";
    cin >> x;

    switch (x)
    {
    case 1:
        calculator();
        break;
    case 2:
        history();
        break;
    case 3:
        cout << "\n\n\nThank you for using my calculator!";
        exit(4);
        break;

    default:
        cout << "Enter a correct choice";
        main();
    }
}

int calculator()
{
    double x, y;
    float sum = 0.0, dif = 0.0, prod = 1.0, quo = 1.0;
    int i;

    char op, back;
    do {
        system("CLS");
        cout << "\t\t#CALCULATOR#" << endl;
        cout << endl << endl;

        cout << "Calculate 2 numbers: (example 1 + 1 or 2 * 2)\n";
        cin >> x >> op >> y;

        switch (op) {

        case '+':
            sum = x + y;
            cout << "The sum of " << x << " and " << y << " is " << sum;
            break;

        case '-':
            dif = x - y;
            cout << "The difference of " << x << " and " << y << " is " << dif;
            break;

        case '*':
            prod = x * y;
            cout << "The product of " << x << " and " << y << " is " << prod;
            break;

        case '/':
            if (y == 0)
                cout << "Undefined";
            else
                quo = x / y;
            cout << "The quotient of " << x << " and " << y << " is " << quo;
            break;

        default:
            cout << "Invalid operator";
            break;
        }

        cout << "\nContinue[Y/N]: ";
        cin >> back;
        cout << endl << endl;
        if (back != 'Y' && back != 'y' && back != 'N' && back != 'n')
        {
            cout << "Please enter a correct choice" << endl;
            choice();
        }
        else if (back == 'N' || back == 'n')
        {
            system("pause");
            system("CLS");
            main();
        }
    } while (back == 'y' || back == 'Y');

    cout << "Thank you";
    system("pause");
    system("CLS");
}

void choice()
{
    char c;
    do
    {
        cout << "Do you want to continue? [Y/y or N/n]" << endl;
        cin >> c;

        if (c == 'Y' || c == 'y')
            calculator();
        else if (c == 'N' || c == 'n')
        {
            system("pause");
            system("cls");
            main();
        }
        else
            cout << "Please enter a correct choice\n";

        choice();


    } while (c != 'y' || c != 'Y' || c != 'N' || c != 'n');
    cout << "Enter a correct choice";
}


void history()
{
    cout << "I still dont know how T - T";
}

解决方案

核心思路

用结构体存储单条计算记录的完整信息,再用全局数组保存所有记录,同时用一个变量追踪已存储的记录数量,最后在历史记录函数里遍历数组输出记录。

修改后的完整代码

#include<iostream>
#include<stdlib.h>

using namespace std;

// 定义计算记录的结构体,包含计算的所有关键信息
struct CalculationRecord {
    double num1;
    char op;
    double num2;
    double result;
    bool isValid; // 标记是否为有效计算(排除除零、无效运算符的情况)
};

// 全局数组存储记录,设置最大存储100条,适合新手入门使用
CalculationRecord historyRecords[100];
int recordCount = 0; // 当前已存储的记录数量

int calculator();
void showHistory(); // 重命名避免和全局变量命名冲突
void choice();

int main()
{
    int x;
    cout << "\t\t\t\tWhat do you want to do?\n\n";
    cout << "\t\t\t\t[1] Standard calculator\n";
    cout << "\t\t\t\t[2] History\n";
    cout << "\t\t\t\t[3] Exit\n\n\n\n";
    cout << "\t\t\t\tChoice: ";
    cin >> x;

    switch (x)
    {
    case 1:
        calculator();
        break;
    case 2:
        showHistory();
        break;
    case 3:
        cout << "\n\n\nThank you for using my calculator!";
        exit(0); // 用0表示正常退出,符合C++规范
        break;

    default:
        cout << "Enter a correct choice\n";
        main();
    }
}

int calculator()
{
    double x, y;
    double result = 0.0;
    char op, back;
    bool isValidCalc = true;

    do {
        system("CLS");
        cout << "\t\t#CALCULATOR#" << endl;
        cout << endl << endl;

        cout << "Calculate 2 numbers: (example 1 + 1 or 2 * 2)\n";
        cin >> x >> op >> y;
        isValidCalc = true;

        switch (op) {
        case '+':
            result = x + y;
            cout << "The sum of " << x << " and " << y << " is " << result;
            break;

        case '-':
            result = x - y;
            cout << "The difference of " << x << " and " << y << " is " << result;
            break;

        case '*':
            result = x * y;
            cout << "The product of " << x << " and " << y << " is " << result;
            break;

        case '/':
            if (y == 0) {
                cout << "Undefined";
                isValidCalc = false; // 除零操作不存入记录
            } else {
                result = x / y;
                cout << "The quotient of " << x << " and " << y << " is " << result;
            }
            break;

        default:
            cout << "Invalid operator";
            isValidCalc = false; // 无效运算符不存入记录
            break;
        }

        // 仅存储有效计算,且数组未存满时才添加记录
        if (isValidCalc && recordCount < 100) {
            historyRecords[recordCount].num1 = x;
            historyRecords[recordCount].op = op;
            historyRecords[recordCount].num2 = y;
            historyRecords[recordCount].result = result;
            historyRecords[recordCount].isValid = true;
            recordCount++;
        }

        cout << "\nContinue[Y/N]: ";
        cin >> back;
        cout << endl << endl;
        if (back != 'Y' && back != 'y' && back != 'N' && back != 'n')
        {
            cout << "Please enter a correct choice" << endl;
            choice();
        }
        else if (back == 'N' || back == 'n')
        {
            system("pause");
            system("CLS");
            main();
        }
    } while (back == 'y' || back == 'Y');

    cout << "Thank you";
    system("pause");
    system("CLS");
    return 0;
}

void choice()
{
    char c;
    do
    {
        cout << "Do you want to continue? [Y/y or N/n]" << endl;
        cin >> c;

        if (c == 'Y' || c == 'y')
            calculator();
        else if (c == 'N' || c == 'n')
        {
            system("pause");
            system("cls");
            main();
        }
        else
            cout << "Please enter a correct choice\n";

    } while (c != 'y' && c != 'Y' && c != 'N' && c != 'n'); // 修正原代码的循环条件错误
}

void showHistory()
{
    system("CLS");
    cout << "\t\t#CALCULATION HISTORY#\n\n";
    if (recordCount == 0) {
        cout << "No calculation records yet.\n";
    } else {
        // 遍历数组输出所有有效记录
        for (int i = 0; i < recordCount; i++) {
            if (historyRecords[i].isValid) {
                cout << i+1 << ". " << historyRecords[i].num1 << " " 
                     << historyRecords[i].op << " " << historyRecords[i].num2 
                     << " = " << historyRecords[i].result << "\n";
            }
        }
    }
    cout << "\nPress any key to go back...";
    system("pause");
    system("CLS");
    main();
}

关键修改点说明

  1. 结构体设计:用CalculationRecord统一存储每条计算的操作数、运算符、结果和有效性,便于管理和展示。
  2. 全局存储容器:全局数组historyRecords和计数器recordCount确保计算函数和历史记录函数能共享数据。
  3. 记录筛选逻辑:仅将有效计算(排除除零、错误运算符)存入数组,保证历史记录的准确性。
  4. 历史记录展示:遍历数组逐条输出记录,无记录时给出提示,提升用户体验。
  5. 原代码修复:修正了choice()函数的循环条件错误,调整了退出码为规范值0。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 14:01:12