【发布时间】:2017-04-19 03:18:44
【问题描述】:
所以我必须编写一个程序,可以从矩阵的对角线确定最大值。比我必须将矩阵的第一个变量 (a[1][1]) 的位置与该矩阵的最大值交换,其他元素保持不变。
这是我的代码:
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int a[20][20];
int main(){
int i, j, n1, n2, max;
printf ("\nIntroduceti numarul de coloane pentru matricea A: ");
scanf (" %d", &n2);
printf ("\nIntroduceti numarul de randuri pentru matricea A: ");
scanf (" %d", &n1);
printf("\nIntroduceti elementele primei matrice: ");
for(i=1;i<=n1;i++){
for(j=1;j<=n2;j++){
printf("\na[%d][%d] = ", i, j);
scanf("%d",&a[i][j]);
}
}
printf("\nMatricea A este:\n");
for(i=1;i<=n1;i++){
printf("\n");
for(j=1;j<=n2;j++){
printf("%d\t",a[i][j]);
}
}
do {
for(i=1;i<=n1;i++){
if(a[i][i]>max) {
max=a[i][i];
}
}
} while (i<=n1);
printf ("\nMaximul de pe diagonala este: %d", max);
a[1][1]=a[1][1]^max;
max=max^a[1][1];
a[1][1]=max^a[1][1];
for(i=1;i<=n1;i++){
printf("\n");
for(j=1;j<=n2;j++){
printf("%d\t",a[i][j]);
}
}
return 0;
}
我做错了什么?我的程序只用第一个变量 a[1][1] 交换最大值,但忘记将 a[1][1] 放在最大值所在的位置。
【问题讨论】:
-
交换背后的逻辑似乎没有错 - 因此标题甚至不相关。
-
在 C 中,数组索引从 0 开始!
-
@ZachP 好吧,逻辑很好,但它没有做我需要它做的事情。我的程序只用第一个变量 a[1][1] 交换最大值,但忘记将 a[1][1] 放在最大值所在的位置。为什么?
-
@NeacsuMihai Take a look here,也许有帮助。
-
为什么要使用异或交换?阅读起来更加令人困惑,并且可能不会使用现代编译器为您带来任何显着的性能提升。 (见Why don't people use xor swaps?。)
标签: c