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

如何在C++二维数组中禁止重复输入值?(仅在main函数实现)

修改后的C++代码(限制二维数组输入无重复值)
#include <iostream>
using namespace std;

int main() {
    
    int num[10][10];
    int times;
    
    cout << "请输入方阵的阶数(不超过10,总元素数不超过100):";
    cin >> times; 
    
    // 阶数合法性检查,避免数组越界
    while (times < 1 || times > 10) {
        cout << "输入非法,请输入1到10之间的整数:";
        cin >> times;
    }
    
    cout << "请输入" << times * times << "个不重复的数字。" << endl;
    
    for(int i = 0; i < times; i++) {
        for(int k = 0; k < times; k++) {
            bool isDuplicate;
            do {
                isDuplicate = false;
                cout << "请输入索引[" << i << "][" << k << "]处的数字:";
                cin >> num[i][k];
                
                // 检查已输入的所有元素是否重复
                for(int x = 0; x < i; x++) {
                    for(int y = 0; y < times; y++) {
                        if(num[x][y] == num[i][k]) {
                            isDuplicate = true;
                            break;
                        }
                    }
                    if(isDuplicate) break;
                }
                // 检查当前行之前的列
                if(!isDuplicate) {
                    for(int y = 0; y < k; y++) {
                        if(num[i][y] == num[i][k]) {
                            isDuplicate = true;
                            break;
                        }
                    }
                }
                
                if(isDuplicate) {
                    cout << "该值已输入过,请重试。" << endl;
                }
            } while(isDuplicate); // 重复输入直到值不重复
        }
    }
    
    // 显示输入结果
    cout << "\n打印数组中的所有值:" << endl; 
    for(int i = 0; i < times; i++) {
        cout << endl;
         for(int k = 0; k < times; k++) {
            cout << "\t" << num[i][k] << " ";     
        }
    }

    return 0;        
}

关键改动说明

  • 添加阶数合法性检查:确保用户输入的times在1到10之间,避免数组越界问题。
  • 用do-while循环处理单元素输入:每次输入后,遍历所有已录入的元素(之前的整行、当前行的前几列)检测重复,若重复则提示并要求重新输入,直到输入合法值。
  • 全中文交互提示:将所有英文提示翻译成符合用户预期的中文表述。

测试示例输出

请输入方阵的阶数(不超过10,总元素数不超过100):2
请输入4个不重复的数字。
请输入索引[0][0]处的数字:7
请输入索引[0][1]处的数字:7
该值已输入过,请重试。
请输入索引[0][1]处的数字:8
请输入索引[1][0]处的数字:7
该值已输入过,请重试。
请输入索引[1][0]处的数字:9
请输入索引[1][1]处的数字:10

打印数组中的所有值:

        7       8 
        9       10 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:01:02