我有一个C代码来生成对角线单位矩阵。代码如下:
#include<stdio.h>
void main()
{
int n,m,a,b,c,d,i,j;
int ar1[100][100];
printf("Enter value of n to create a square matrix of order n (odd no.): ");
scanf("%d", &n);
printf(" matrix in diagonal direction is - \n");
for (i=0; i<n; i++) {
for (j=0; j<n; j++) {
if (ar1[j]==ar1[i]) {
ar1[j][i] = 2;
printf("%d, ", ar1[j][i]);
} else {
ar1[j][i] = -1;
printf("%d, ", ar1[j][i]);
}
}
printf("\n");
}
}
给我一个这样的结果:
2, -1, -1, -1, -1,
-1, 2, -1, -1, -1,
-1, -1, 2, -1, -1,
-1, -1, -1, 2, -1,
-1, -1, -1, -1, 2
但我想在相反方向打印对角矩阵,如下所示:
-1, -1, -1, -1, 2,
-1, -1, -1, 2, -1,
-1, -1, 2, -1, -1,
-1, 2, -1, -1, -1,
2, -1, -1, -1, -1
有人可以帮我解决一下如何在相反方向打印对角矩阵吗?我想改变实际矩阵而不仅仅是输出
我已经像这样更新了我的代码(如下所示),但我仍然收到错误(如下所示)
#include<stdio.h>
void main()
{
int n,m,a,b,c,d,i,j,s;
int ar1[100][100];
printf("Enter value of n to create a square matrix of order n (odd no.): ");
scanf("%d",&n);
printf("Enter m: (odd no.) ");
scanf("%d",&m );
if(n>m)
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
for(a=1;a<=(m-1)/2;a++){
if(ar1[i-a]==ar1[j]){
ar1[i][j] = 2;
printf("%d, ",ar1[i][j]);
}
}
for(a=(m+1)/2;a<=(n-1);a++){
if(ar1[i-a]==ar1[j]){
ar1[i][j] = -1;
printf("%d, ",ar1[i][j]);
}
}
if(ar1[i]==ar1[j]){
ar1[i][j] = 2;
printf("%d, ",ar1[i][j]);
}
for(a=1;a<=(m-1)/2;a++){
if(ar1[i+a]==ar1[j]){
ar1[i][j] = 2;
printf("%d, ",ar1[i][j]);
}
}
for(a=(m+1)/2;a<=(n-1);a++){
if(ar1[i+a]==ar1[j]){
ar1[i][j] = -1;
printf("%d, ",ar1[i][j]);
}
}
s = flip (ar1[100][100], n);
}
printf("\n");
}
void flip(int a[100][100], int n) {
int t;
for (i=0; i<n; i++) {
for (j=0; j<n/2; j++) {
t=a[i][j];
a[i][j] = a[i][n-1-j];
a[i][n-1-j] = t;
}
}
}
}
}
我遇到了这样的错误
/tmp/cc72v9hd.o: In function `main':
faltu2.c:(.text+0x629): undefined reference to `flip'
collect2: ld returned 1 exit status
答案 0 :(得分:1)
只需撤消任何循环,即从n-1
迭代应该这样做。下面是我的版本,
#include<stdio.h>
void main()
{
int n,m,a,b,c,d,i,j;
int ar1[100][100];
printf("Enter value of n to create a square matrix of order n (odd no.): ");
scanf("%d",&n);
printf(" matrix in diagonal direction is - \n");
for(i=0;i<n;i++)
{
for(j=n-1;j>=0;j--)
{
//if(ar1[j]==ar1[i]){ // any two garbage values can be equal
if(j==i)
{
ar1[j][i] = 2;
printf("%d, ",ar1[j][i]);
}
else
{
ar1[j][i] = -1;
printf("%d, ",ar1[j][i]);
}
}
printf("\n");
}
}
答案 1 :(得分:1)
如果您只想更改输出而不是实际矩阵,只需替换此外循环:
for (i=0; i<n; i++) {
...
这一个:
for (i=n-1; i>=0; i--) {
...
<强>更新即可。如果你需要翻转矩阵,只需使用这样的函数或代码:
void flip(int a[][], int n) {
int i,j,t;
for (i=0; i<n; i++) {
for (j=0; j<n/2; i++) {
t=a[i][j];
a[i][j] = a[i][n-1-j];
a[i][n-1-j] = t;
}
}
}