【问题标题】:Copying each row of matrix to a temporary array将矩阵的每一行复制到一个临时数组
【发布时间】:2013-07-18 14:36:07
【问题描述】:

我想将 500x8 matrix 的一行(每个团队迭代一个)复制到名为 actual_row 的临时数组中。这是我尝试过的。

int matrix[500][8]; // this has been already filled by int's
int actual_row[8];
for(int i = 0; i < 500; i++) {
     for(int j = 0; j < 8; j++) {
         actual_row[j] = matrix[i][j];
         printf("The row is: ");
         for(int q = 0; q < 8; q++) {
                 printf(" %d ",actual_row[q]);
         // do other stuff
         }
      }
printf("\n");
}

这不是打印行,它有时会打印 0 和 1,所以我做错了。
提前致谢。

【问题讨论】:

    标签: c arrays matrix


    【解决方案1】:

    actual_row 在填满之前不要打印:

     for(int j = 0; j < 8; j++) {
         actual_row[j] = matrix[i][j];
     }
    
     printf("The row is: ");
     for(int q = 0; q < 8; q++) {
          printf(" %d ",actual_row[q]);
          ...
     }
    

    【讨论】:

      【解决方案2】:

      你的逻辑有点不对劲。您需要将该行复制到actual_row,然后打印内容。此外,为什么不在将矩阵行复制到actual_row 时打印内容:

      printf("The row is: ");
      for(int j = 0; j < 8; j++) {
          actual_row[j] = matrix[i][j];         
          printf(" %d ",actual_row[j]);
          // do other stuff
      }
      

      所以你的代码 sn-p 应该是这样的:

      int matrix[500][8]; // this has been already filled by int's
      int actual_row[8];
      for(int i = 0; i < 500; i++) {
          printf("The row is: ");
          for(int j = 0; j < 8; j++) {
              actual_row[j] = matrix[i][j];         
              printf(" %d ",actual_row[j]);
             // do other stuff
          }
          // <--at this point, actual_row fully contains your row
       printf("\n");
      }
      

      【讨论】:

        【解决方案3】:

        您的逻辑有点偏离(不需要第三个嵌套循环)。您需要将该行复制到actual_row(您已这样做),并在同一循环中打印内容:

         printf("The row is: ");
         for(int j = 0; j < 8; j++) {
             actual_row[j] = matrix[i][j];         
             printf(" %d ",actual_row[j]);
             // do other stuff
         }
        

        【讨论】:

          猜你喜欢
          • 2019-04-13
          • 2017-07-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多