我编写了一个程序,我的教授希望我按照她想要的方式专门制作,但是输出与正确的输出不同。
这是我的代码:
#include <stdio.h>
#define N 16
int xchg(int *a, int *b);
int main (){
int i, j, k, count;
int Num[N] = {7, 1, 993, -5, 0, 16, -451, 12, 89,28, 77, 384, -2, 38, -17, 201};
for(i = 0; i <= N - 1; i++){
for(j = i + 1; j <= N; j++){
count += xchg(&Num[i], &Num[j]);
}
for(k = 0; k < N; k++){
if(k <= 15){
printf("%d ", Num[k]);
}
else
printf("%d", Num[k]);
}
printf("\n");
}
printf("total exchanges: %d\n", count);
}
int xchg(int *a, int *b){
int c;
if ( *a > *b )
c = 1;
else
c = 0;
return c;
}
这是输出:
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
7 1 993 -5 0 16 -451 12 89 28 77 384 -2 38 -17 201
total exchanges: 1
这是正确的输出:
-451 7 993 1 0 16 -5 12 89 28 77 384 -2 38 -17 201
-451 -17 993 7 1 16 0 12 89 28 77 384 -2 38 -5 201
-451 -17 -5 993 7 16 1 12 89 28 77 384 0 38 -2 201
-451 -17 -5 -2 993 16 7 12 89 28 77 384 1 38 0 201
-451 -17 -5 -2 0 993 16 12 89 28 77 384 7 38 1 201
-451 -17 -5 -2 0 1 993 16 89 28 77 384 12 38 7 201
-451 -17 -5 -2 0 1 7 993 89 28 77 384 16 38 12 201
-451 -17 -5 -2 0 1 7 12 993 89 77 384 28 38 16 201
-451 -17 -5 -2 0 1 7 12 16 993 89 384 77 38 28 201
-451 -17 -5 -2 0 1 7 12 16 28 993 384 89 77 38 201
-451 -17 -5 -2 0 1 7 12 16 28 38 993 384 89 77 201
-451 -17 -5 -2 0 1 7 12 16 28 38 77 993 384 89 201
-451 -17 -5 -2 0 1 7 12 16 28 38 77 89 993 384 201
-451 -17 -5 -2 0 1 7 12 16 28 38 77 89 201 993 384
-451 -17 -5 -2 0 1 7 12 16 28 38 77 89 201 384 993
total exchanges:51
请帮我将我的输出变成正确的输出!我只编码了三个月,所以我对基本错误表示歉意。
最佳答案
#include <stdio.h>
#define N 16
int xchg(int *a, int *b);
int main (void){
int i, j, k, count = 0;
int Num[N] = {7, 1, 993, -5, 0, 16, -451, 12, 89,28, 77, 384, -2, 38, -17, 201};
for(i = 0; i < N - 1; i++){
for(j = i + 1; j < N; j++){
count += xchg(&Num[i], &Num[j]);
}
for(k = 0; k < N; k++){
if(k < N-1){
printf("%d ", Num[k]);
} else {
printf("%d", Num[k]);
}
}
printf("\n");
}
printf("total exchanges: %d\n", count);
}
int xchg(int *a, int *b){
int s = (*a > *b);
if(s){
int t = *a;
*a = *b;
*b = t;
}
return s;
}
关于c - 实验室代码逻辑错误,C程序初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31507690/