C程序只工作一部分



我需要制作一个程序,说我必须在奇数行中填充"1",在偶数行中填充"0"。我尝试并编写了这段代码,但它似乎只适用于一部分。拜托,你能解释一下方法吗?

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
main()
{
  int r, c;
  do {
  printf("Insert the number of the rows in the matrix: ");
  scanf("%d", &r);
  printf("Insert the number of the colums in the matrix: ");
  scanf("%d", &c);
  } while(r<=0||c<=0);
  r--; c--;
  int mat[r][c];
  int a, b;
  for(a=0; a<=r; a++)
  {
    for(b=0; b<=c; b++)
    {
      if(a%2==0)
      {mat[a][b]=0;}
      else {mat[a][b]=1;}
    }
  }
  printf("nOUTPUT:nn");
    for(a=0; a<=r; a++){
      for(b=0; b<=c; b++){
        printf("%d", mat[a][b]);
      }
      printf("n");
    }
  return 0;
}

输入: 2, 3

输出:001111

您没有正确使用行数和列数。的确,在 C 中,具有 N 个条目的数组只能访问索引 0 到 N - 1,并且索引N超出了数组的范围。但是您仍然必须使用实际大小定义数组:

// Don't adjust c and r here
int mat[r][c];

for循环中使用维度时,可以使用<而不是<=作为条件来确保永远不会访问mat[r][c]

for (a = 0; a < r; a++) {
    for (b = 0; b < c; b++) {
        if (a % 2 == 0) {
            mat[a][b] = 0;
        } else {
            mat[a][b] = 1;
        }
    }
}

你弄乱了矩阵的大小。您可能想更改这两个的顺序并尝试一下:

r--; c--;
int mat[r][c];

将其更改为

int mat[r][c];
r--; c--;

并且代码应该按预期工作。

最新更新