【问题标题】:Printing out a 2d array in a specific format in C在 C 中以特定格式打印出二维数组
【发布时间】:2015-09-27 13:04:58
【问题描述】:

所以基本上当我打印我的数组时,它看起来像这样:

      P00       P01       P02      
      P10       P11       P12       
      P20       P21       P22 

我希望它看起来像这样:

             M[0][0]   M[0][1]   M[0][2]   
      M[0][0] P00       P01       P02       
      M[1][0] P10       P11       P12      
      M[2][0] P20       P21       P22      

我的代码:

 for (z=0; z<N; z++){

              for (c=0; c<N;c++){
                printf("\t%p", &M[z][c]);
    }
    printf("\n");
          }

注意Pxx是指针地址

【问题讨论】:

  • 对于可移植代码,使用printf("\t%p", (void *) &amp;M[z][c]); 如果M[][] 还没有准备好void *,则添加演员表。
  • 但有一点,这些不是矩阵的正确索引。您是说,当您给出的坐标都与矩阵本身中的一个位置相关时,每一行/列中的所有内容都是该矩阵点。(0,0)!=(0,1)。您必须基本上按照 Pxx 语句的放置方式将位置放置在每个点。基本上。而不是在你的 M[x][x] 中放置两个点只需将一个作为索引 m[Var]

标签: c arrays 2d


【解决方案1】:

在外循环之上:

printf("\t\tM[0][0]\tM[0][1]\tM[0][2]\n");

然后在外循环下方:

printf("M[%d][0]\t",i);

看起来像这样:

printf("\t\t");

for (z=0; z<N; z++)
  printf("\tM[0][%d]",z);

printf("\n");

for ( z=0; z<N; z++){
   printf("M[%d][0]\t",z);
   for(c=0; c<N; c++){
      printf("\t%p",&M[z][c]);
   }
   printf("\n");
 }

【讨论】:

    【解决方案2】:

    可能是这样的:

    for(i=0;i<N;i++){
            printf("\tM[0][%d]",i);
        }        
        printf("\n");
    for (z=0; z<N; z++){
        printf("M[%d][0]",z);
        for (c=0; c<N;c++){
    
            printf(" %p\t", &M[z][c]);
        }
    printf("\n");
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-01
      • 1970-01-01
      • 2012-10-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      • 1970-01-01
      相关资源
      最近更新 更多