加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

模式打印 – 这个C代码我哪里错了?

发布时间:2020-12-16 10:07:35 所属栏目:百科 来源:网络整理
导读:我写了一个程序来打印一个N×N方形图案,交替0和1.例如.一个5 x 5的正方形看起来像这样: 我使用以下代码 – #includeiostream.hint main(){ int i,n; cin n; //number of rows (and columns) in the n x n matrix for(i = 1; i = n*n; i++) { cout " " i%2;
我写了一个程序来打印一个N×N方形图案,交替0和1.例如.一个5 x 5的正方形看起来像这样:

enter image description here

我使用以下代码 –

#include<iostream.h>
int main()
{
  int i,n;
  cin >> n; //number of rows (and columns) in the n x n matrix
  for(i = 1; i <= n*n; i++)
  {
    cout << " " << i%2;
    if(i%n == 0)
    cout << "n";
  }

  fflush(stdin);
  getchar();
  return 0;
}

这个代码适用于奇数,但对于偶数,它在每个新行中打印相同的东西,而不是交替模式.对于4它打印这个 –

enter image description here

我哪里错了?

解决方法

在我看来,迭代矩阵的最好方法是在另一个循环中使用循环.

我认为这段代码对您有所帮助:

for(i = 0; i < n; i++) {
    for (j = 1; j <= n; j++) {
        cout<<" "<< (j + i) % 2;
    }
    cout<<"n";
}

其中n是行数,i和j是整数.

试着理解它为什么以及如何运作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读