仅打印阵列的某些元素

时间:2015-10-28 15:46:44

标签: 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: "<<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;
    }

}

如果我输入例如4行和4列,我输入以下数字,以便可以这样打印出来:

1 2 3 4
5 6 7 8
9 0 11 12
13 14 15 16

我想要这样的输出:

1 3
6 8
9 11
14 16

谢谢你提前!

4 个答案:

答案 0 :(得分:1)

添加嵌套循环仅在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];
    }
 }

答案 1 :(得分:0)

您可以将此for循环用于打印:

Warning: Creating default object from empty value in D:\xampp\htdocs\moodel\server\moodle\config.php on line 5

这种方式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; } 索引在每次迭代中前进2。并从每行的不同索引0或1开始

答案 2 :(得分:0)

使用模数检查每个单元格中索引的“等级”:

if((x+i)%2 == 0)

然后打印出来,当评估为真时,他会重视。

Lasoloz

答案 3 :(得分:0)

首先考虑到C ++中没有可变长度数组(VLA)。因此,您的代码可能无法使用其他编译器进行编译。

您要完成的任务可以非常简单地完成。:)

只需写下

for ( int i = 0; i < m; i++ )
{
    for ( int x = i % 2; x < n; x += 2) cout << arr[i][x] <<" ";
                  ^^^^^^        ^^^^^^
    cout << endl;
}
相关问题