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

如何修改C++的procedure1函数,实现单次输入并依次填充数组元素?

解决方案

要实现每次调用procedure1仅输入一个数字并依次存入数组对应索引,核心是需要跟踪当前已输入的位置,避免一次性循环填充整个数组。以下是两种可行的实现方式:

推荐方案:使用引用参数跟踪索引

这种方式灵活且无副作用,适合处理多个数组的场景:

修改后的函数代码

void procedure1(int Num1[], int& currentIndex, int size = 10)
{
    // 检查数组是否已填满,避免越界访问
    if (currentIndex >= size) {
        cout << "数组已满,无法继续输入!" << endl;
        return;
    }
    
    cout << "Input a number: ";
    cin >> Num1[currentIndex];
    // 输入完成后索引自增,下次调用自动指向下一个位置
    currentIndex++;
}

主程序调用示例

#include <iostream>
using namespace std;

// 放置上面的procedure1函数

int main() {
    const int ARRAY_CAPACITY = 10;
    int numArray[ARRAY_CAPACITY];
    int currentPosition = 0; // 初始索引为0,记录当前要写入的位置
    int menuChoice;

    do {
        // 主菜单逻辑
        cout << "\n=== 主菜单 ===" << endl;
        cout << "1. 输入一个数字" << endl;
        cout << "2. 查看已输入的数字" << endl;
        cout << "3. 退出程序" << endl;
        cout << "请选择操作: ";
        cin >> menuChoice;

        switch(menuChoice) {
            case 1:
                procedure1(numArray, currentPosition, ARRAY_CAPACITY);
                break;
            case 2:
                cout << "已输入的数字: ";
                for (int i = 0; i < currentPosition; i++) {
                    cout << numArray[i] << " ";
                }
                cout << endl;
                break;
            case 3:
                cout << "程序已退出。" << endl;
                break;
            default:
                cout << "无效选项,请重新选择!" << endl;
        }
    } while (menuChoice != 3);

    return 0;
}

备选方案:使用静态变量(仅适合单数组场景)

静态变量会在函数第一次调用时初始化,后续调用保留值,但如果用于多个数组会导致索引混乱,仅推荐单数组场景使用:

void procedure1(int Num1[], int size = 10)
{
    static int currentIndex = 0; // 静态变量,仅初始化一次
    if (currentIndex >= size) {
        cout << "数组已满,无法继续输入!" << endl;
        return;
    }
    
    cout << "Input a number: ";
    cin >> Num1[currentIndex];
    currentIndex++;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 21:30:12