简体   繁体   English

c程序中的对称矩阵二维数组

[英]symmetric matrix 2-d array in c program

the program should this:该程序应该:

the matrix use 1,2,...,n on first line and 2,3,...n,n-1 on second etc, for instance :矩阵在第一行使用 1,2,...,n ,在第二行使用 2,3,...n,n-1 等,例如:

input :输入 :

5

expected output:预期输出:

1 2 3 4 5
2 3 4 5 4
3 4 5 4 3
4 5 4 3 2
5 4 3 2 1

i get try maybe anyone can help me to solve this program.我得到尝试也许任何人都可以帮助我解决这个程序。

this my program before:这是我之前的程序:

#include <stdio.h>

void makeSymmetricMatrix(int n) {
    int i,j;
   int matrix[n][n];
   for( i = 0; i<n; i++){
      int count = 1;
      for( j = 0; j <n; j++){
         if(i == j){
            matrix[i][j] = 0;
         }else{
            matrix[i][j] = count++;
         }
      }
   }
   for( i = 0; i<n; i++){
      for( j = 0; j <n; j++){
         printf("%d", matrix[i][j]);
      }
      printf("\n");
   }
}
int main() {
   int n = 5;
   makeSymmetricMatrix(n);
}

I really need your correction about my program我真的需要你更正我的程序

can be done using :可以使用:

void makeSymmetricMatrix(int n) {
  int i,j;
  int matrix[n][n];
  
  for (i = 0; i<n; i++) {
    int v = i+1, offset = 1;
    
    for (j = 0; j <n; j++){
      matrix[i][j] = v;
      if (v == n)
        offset = -1;
      v += offset;
    }
  }
  for( i = 0; i<n; i++){
    for( j = 0; j <n; j++){
      printf("%d ", matrix[i][j]);
    }
    putchar('\n');
  }
}

in each line the first value equals the rank of the line plus 1 and by default the next value is the current plus 1在每一行中,第一个值等于该行的排名加 1,默认情况下,下一个值是当前值加 1

each time the value reaches n the rest of the values of the same line are the previous minus 1每次该值达到n时,同一行的其余值都是前一个负 1

After the change compilation and execution :更改编译和执行后:

pi@raspberrypi:/tmp $ gcc -Wall m.c
pi@raspberrypi:/tmp $ ./a.out
1 2 3 4 5 
2 3 4 5 4 
3 4 5 4 3 
4 5 4 3 2 
5 4 3 2 1 
pi@raspberrypi:/tmp $ 

Try this function.试试这个功能。

void makeSymmetricMatrix(int n)
{
    int i, j, count, decrease;
    int matrix[n][n];

    for(i = 0; i < n; i++)
    {
        decrease = 0;
        count = i+1;
        for(j = 0; j < n; j++)
        {
            matrix[i][j] = count;
            if(count == n)
                decrease = 1;

            if(decrease == 1)
                count--;
            else
                count++;
        }
    }

    for( i = 0; i<n; i++){
      for( j = 0; j <n; j++){
         printf("%d", matrix[i][j]);
      }
      printf("\n");
   }
}

Basically it stores a variable decrease which gets triggered when count reaches the maximum value ( n here).基本上它存储一个变量decrease ,当count达到最大值(此处为n )时触发。 Once that happens, numbers are stored in a reverse order.一旦发生这种情况,数字将以相反的顺序存储。

Result for n = 6 : n = 6结果:

123456
234565
345654
456543
565432
654321

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM