【问题标题】:Printing only some elements of an array仅打印数组的某些元素
【发布时间】:2016-01-28 11:49:09
【问题描述】:

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

#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

先谢谢了!

【问题讨论】:

  • 这与问题无关,如果我错了请纠正我,但我对c++的理解是你不能用编译后时间变量分配数组的大小,即编译器编译前需要知道数组的大小。

标签: c++ arrays for-loop multidimensional-array


【解决方案1】:

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

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

随便写

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

【讨论】:

    【解决方案2】:

    您可以使用此 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;
    }
    

    这样x 索引在每次迭代中前进 2。每行从不同的索引 0 或 1 开始

    【讨论】:

    • 感谢您抽出宝贵时间回答!但是我已经这样做了,当我想要代表“白色”方块的 1,3,6,8,9,11,14,16 时,它会打印 1,3,5,7,9,11,13,15。
    • 它需要对cout &lt;&lt; endl; 再进行一次编辑,现在它会产生预期的输出
    【解决方案3】:

    用模数检查每个单元格的索引“排名”:

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

    然后打印出来,当判断为真时,他的值。

    拉索洛兹

    【讨论】:

      【解决方案4】:

      添加一个嵌套循环,只在 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];
          }
       }
      

      【讨论】:

        猜你喜欢
        • 2014-12-08
        • 1970-01-01
        • 1970-01-01
        • 2021-08-13
        • 2016-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多