C++ 仅打印数组的某些元素

C++ 仅打印数组的某些元素,c++,arrays,for-loop,multidimensional-array,C++,Arrays,For Loop,Multidimensional Array,我想问你们,我怎样才能打印一个二维数组,使它看起来像一个棋盘,并且只打印白色的数字 #include <iostream> using namespace std; int main() { int m; int n; cout<<"Enter the amount of rows: "<<endl; cin>>m; cout<<"Enter the amount of columns: "&

我想问你们,我怎样才能打印一个二维数组,使它看起来像一个棋盘,并且只打印白色的数字

#include <iostream>

using namespace std;

int main()
{
    int m;
    int n;
    cout<<"Enter the amount of rows: "<<endl;
    cin>>m;
    cout<<"Enter the amount of columns: "<<endl;
    cin>>n;
    if(!cin){
        cout<<"Error.Bad input."<<endl;
        return 1;
    }
    double arr[m][n];
    cout<<"Enter the element of the array: "<<endl;
    for (int i=0;i<m;i++){
    for(int x = 0;x<n;x++){
        cin>>arr[i][x];
    }
    }
    cout<<"Printed array like a chessboard: "<<endl;
    for(int i=0;i<m;i++){
        for(int x=0;x<n;x++){
        cout<<arr[i][x]<<" ";
        }cout<<endl;
    }

}
我想要这样的输出:

1 3
6 8
9 11
14 16

感谢是前进

您可以使用此for循环进行打印:

for(int i = 0; i < m; i += 2){
    for(int x = 0; x < n; x += 2){
        cout << arr[i][x] << " ";
    }
    cout << endl;
    for(int x = 1; x < n; x += 2){
        cout << arr[i + 1][x] << " ";
    }
    cout << endl;
}
for(int i=0;icout添加嵌套循环以仅在i+x为偶数时打印:

 for (int i=0;i<m;i++){
    for(int x = 0;x<n;x++){
     if ((i + x) % 2 == 0)
        cout<<arr[i][x];
    }
 }
for(int i=0;i在每个单元格中检查带模索引的“秩”:

if((x+i)%2 == 0)
然后打印出来,当计算结果为真时,他会计算值


<> LasoOz

< P>首先考虑C++中没有可变长度数组(VLA),因此您的代码可能不会使用其他编译器编译。 您尝试完成的任务可以非常简单地完成。:)

只要写

for ( int i = 0; i < m; i++ )
{
    for ( int x = i % 2; x < n; x += 2) cout << arr[i][x] <<" ";
                  ^^^^^^        ^^^^^^
    cout << endl;
}
for(int i=0;i对于(int x=i%2;xcout
for ( int i = 0; i < m; i++ )
{
    for ( int x = i % 2; x < n; x += 2) cout << arr[i][x] <<" ";
                  ^^^^^^        ^^^^^^
    cout << endl;
}