首页 > 解决方案 > 在二维数组中查找“x”数时出现 C++ 错误

问题描述

在下面的代码中,我尝试在二维数组中找到一个“x”并显示它的行和列。但它总是a[0][1]在结果中显示。有人能告诉我我哪里做错了吗,为什么?我尝试了其他代码,但没有区别。谢谢

我的代码:

#include <iostream>
using namespace std;
int main(){
    int m, n, i, j, a[m][n], sum, x, sl=0;
    cout<<"insert array number of rows: "; cin>>m;
    cout<<"insert array number of columns: "; cin>>n;
    for(i=0;i<m;i++){
        sum=0;
        for(j=0;j<n;j++){
            cout<<"insert board["<<i<<"]["<<j<<"]: ";
            cin>>a[i][j];
            sum+=a[i][j];
        }
        cout<<"the summary of rows "<<i<<" is: "<<sum<<endl;
    }
    cout<<"search x= "; cin>>x;
    for (i=0; i<=m-1; i++){
        for (j=0; j<=n-1; j++){
            if (a[i][j]==x){
                sl++;
                cout<<"x is at "<<"a["<<i<<"]["<<j<<"]"<< endl;
            }
        }
    }
    if(sl==0){
        cout<<"there is no x in the array";
    }
    cout<<sl;
    return 0;
}

我的结果:

我的结果

标签: c++

解决方案


代码中的错误来源:

您使用的是可变长度数组(这不是 C++ 标准的一部分)。此外,您甚至在初始化/输入nm.

固定代码:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    int m, n, x, sl = 0;

    cout << "Insert number of rows in the array: ";
    cin >> m;
    cout << "\nInsert number of columns in the array: ";
    cin >> n;

    // put the below line after cin >> m; cin >> n;
    vector<vector<int>> a(m, vector<int>(n, 0));  // <-- Use this instead of int a[m][n];

    cout << endl;
    
    for (int i = 0; i < m; ++i) {
        int sum = 0;
        for (int j = 0; j < n; ++j) {
            cout << "\nInsert board[" << i << "][" << j << "]: ";
            cin >> a[i][j];
            sum += a[i][j];
        }
        cout << "\nThe sum of the row " << i << " is: " << sum << endl;
    }

    cout << "\nSearch x = ";
    cin >> x;
    
    cout << '\n' << endl;

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (a[i][j] == x) {
                sl++;
                cout << "x is at a[" << i << "][" << j << "]\n";
            }
        }
    }

    if (sl == 0) { cout << "\nThere is no x in the array!"; }
    else cout << '\n' << sl;

    return 0;
}

样本输入:

2
2
3
4
7
3
3

样本输出:

Insert number of rows in the array: 
Insert number of columns in the array: 

Insert board[0][0]: 
Insert board[0][1]: 
The sum of the row 0 is: 7

Insert board[1][0]: 
Insert board[1][1]: 
The sum of the row 1 is: 10

Search x = 

x is at a[0][0]
x is at a[1][1]

2

对于交互式运行,您可以根据需要删除换行符。


推荐阅读