這是main調用的代碼,用C語言中的選擇排序對數組進行排序。我在main中打開一個文件,並將前十個整型放入一個數組中,將第11個整型放入一個變量中,然後調用一堆簡單函數。整件事重複了三次。對於我的測試文件,最後兩個迭代具有正確的打印排序,但第一個以0開頭,但我的數組中沒有0。它也會丟棄最後一個int。對於這個選擇排序,爲什麼當我的數組中沒有使用0時,第一個數字是0? (in c)
在此先感謝您的幫助!
這裏是我的代碼:
void sortme (int arry [], int last_int)
{
int temp;
int smallest_int;
int current_int;
int target_searcher;
int numPrinted;
for(current_int = 0; current_int < last_int; current_int++)
{
smallest_int = current_int;
for(target_searcher = current_int + 1; target_searcher <= last_int; target_searcher++)
if(arry[target_searcher] < arry[smallest_int])
smallest_int = target_searcher;
temp = arry[current_int];
arry[current_int] = arry[smallest_int];
arry[smallest_int] = temp;
} //end outter loop
numPrinted = 0;
printf("\nThe sorted array is: ");
for(current_int = 0; current_int < SIZE; current_int++)
{
printf("%4d", arry[current_int]);
if(numPrinted < COUNT)
numPrinted++;
else
{
printf("\n");
numPrinted = 0;
}
}
printf("\n");
return;
}
這裏是我的參考輸出(大部分的東西main.c中被commenetd出):
The file opened.
Scanned into a[] and target is 33
ARRAY[1]
The contents in the array are: 40 32 57 27 67 6 3 89 2 99
The sorted array is: 0 2 3 6 27 32 40 57 67 89
The value searched, 33, was not found.
Scanned into a[] and target is 3
ARRAY[2]
The contents in the array are: 86 43 89 32 45 12 1 58 98 4
The sorted array is: 1 4 12 32 43 45 58 86 89 98
The value searched, 3, was not found.
Scanned into a[] and target is 11
ARRAY[3]
The contents in the array are: 1 2 3 4 5 6 7 8 9 10
The sorted array is: 1 2 3 4 5 6 7 8 9 10
The value searched, 11, was not found.
Closing the file.
The file closed.
你試過調試過嗎?嘗試一個非常小的數組(例如,只有1個條目)。通過你的'for(current_int = 0; current_int
@Raymond是對的:用調試器進行調試和進入代碼絕對是**強制**。如果你不知道如何,你必須學習。如果你知道如何,並選擇不去,你錯了。 – abelenky
調試與在printf語句中添加以幫助查看程序粘在哪裏相同?我們還沒有在課堂上進行調試(我在編程方面很新穎)。 – Piseagan