代碼:
#include <stdio.h>
int main() {
int i, j, temp, a[10] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }, n = 10;
printf("Before sorting, the array is:");
for (i = 0; i < n; i )
printf("%d ", a[i]);
for (i = 0; i < n - 1; i ) {
temp = i;
for (j = i 1; j < n; j ) {
if (a[j] < a[temp])
temp = j;
}
if (temp != i) {//for swapping
a[j] = a[j] a[temp];
a[temp] = a[j] - a[temp];
a[j] = a[j] - a[temp];
}
}
printf("\nAfter sorting, the array is:");
for (i = 0; i < n; i )
printf("%d ", a[i]);
return 0;
}
輸出:

未列印排序值。這段代碼的錯誤在哪里?
uj5u.com熱心網友回復:
您列出的代碼產生的輸出是:
Before sorting, the array is:9 8 7 6 5 4 3 2 1 0
After sorting, the array is:9 8 7 6 5 4 3 2 0 4198464
關聯:
https://godbolt.org/z/o3nfz9Yv3
最后的垃圾似乎是這段代碼的結果:
if(temp!=i)
{//for swapping
a[j]=a[j] a[temp];
a[temp]=a[j]-a[temp];
a[j]=a[j]-a[temp];
}
當此代碼執行時,j總是等于n,這意味著您總是訪問 上的無效資料a[j]。我想你的意思是用 'i' 代替 'j'。
uj5u.com熱心網友回復:
輸出不會出現,因為您沒有在數字后列印換行符。某些系統需要這樣做才能獲得正確的輸出。
但是請注意,交換代碼是不正確的:您應該交換a[temp]和a[i],而不是a[j]。
通過加減來交換值是不正確的:它不適用于浮點值和非數字型別,并且在溢位的情況下對有符號整數具有未定義的行為。您應該使用臨時變數:
#include <stdio.h>
int main() {
int i, j, temp;
int a[10] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting, the array is:");
for (i = 0; i < n; i ) {
printf(" %d", a[i]);
}
printf("\n");
for (i = 0; i < n - 1; i ) {
temp = i;
for (j = i 1; j < n; j ) {
if (a[j] < a[temp])
temp = j;
}
if (temp != i) {//for swapping
int t = a[temp];
a[temp] = a[i];
a[i] = t;
}
}
printf("After sorting, the array is:");
for (i = 0; i < n; i ) {
printf(" %d", a[i]);
}
printf("\n");
return 0;
}
uj5u.com熱心網友回復:
看來,你有一個簡單的錯字:你應該使用i索引而不是j在交換片段中:
當前的代碼有a[j],這是不正確的,因為j == n你嘗試這是一個專案操縱出的0 .. n - 1 范圍:
if (temp != i) {//for swapping
a[j] = a[j] a[temp]; // <- a[j] is in fact a[n] here
a[temp] = a[j] - a[temp];
a[j] = a[j] - a[temp];
}
應該是a[i],我們交換當前a[i]和找到的a[temp]專案:
if (temp != i) {//for swapping
a[i] = a[i] a[temp];
a[temp] = a[i] - a[temp];
a[i] = a[i] - a[temp];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/381480.html
