2012-03-06 58 views
0

我在做選擇排序。我寫的程序產生錯誤的結果,但是當我從一個網站複製它時。代碼完全一樣,但從網站複製的代碼有更多空格。我提供了這兩個代碼。請幫助 我寫的代碼:程序在寫入時給出錯誤的答案,但在複製時給出正確的答案

#include<stdio.h> 
main() 
{ 
int position, array[100], n, c, d, swap; 
printf ("Enter the number of elements:\n"); 
scanf ("%d", &n); 
printf ("Enter the %d integer\n",n); 
for (c=0 ; c < n ; c++) 
scanf ("%d", &array[c]); 
for (c = 0 ; c < (n-1); c++) 
{ 
position=c; 
for (d = c+1; d < n; d++) 
{ 
if (array[position] > array[d]); 
position = d; 
} 
if (position !=c); 
{ 
swap = array[c]; 
array[c] = array[position]; 
array[position] = swap; 
} 
} 
printf ("Sorted list in the ascending order:\n"); 
for (c=0 ; c < n ; c++) 
printf ("%d\n", array[c]); 
getch(); 
} 

在網站

#include<stdio.h> 

main() 
{ 
    int array[100], n, c, d, position, swap; 

    printf("Enter number of elements\n"); 
    scanf("%d", &n); 

    printf("Enter %d integers\n", n); 

    for (c = 0 ; c < n ; c++) 
     scanf("%d", &array[c]); 

    for (c = 0 ; c < (n - 1) ; c++) 
    { 
     position = c; 

     for (d = c + 1 ; d < n ; d++) 
     { 
     if (array[position] > array[d]) 
      position = d; 
     } 
     if (position != c) 
     { 
     swap = array[c]; 
     array[c] = array[position]; 
     array[position] = swap; 
     } 
    } 

    printf("Sorted list in ascending order:\n"); 

    for (c = 0 ; c < n ; c++) 
     printf("%d\n", array[c]); 

    getch(); 
} 
+3

如果您使用了像AStyle這樣漂亮的打印程序,那麼您會注意到由縮進引起的錯誤。 – Benoit 2012-03-06 15:09:25

+3

這只是複製家庭作業的作品。大聲笑。 – honeyp0t 2012-03-06 15:09:52

+1

正如Paul R的答案所建議的那樣,您只需讓代碼正確縮進即可看到問題所在。投票結束。 – 2012-03-06 15:10:02

回答

10

給他們是不一樣的代碼 - 在一個你有:

if (array[position] > array[d]); 
position = d; 

而在其他你有:

 if (array[position] > array[d]) 
     position = d; 

注意第一個中的雜散分號,它完全改變了程序的語義。

請注意,您應該在編譯時啓用警告(例如gcc -Wall) - 這有助於捕獲愚蠢但難以實現的錯誤,例如上述示例。


編輯正如@Lucas注意到,你似乎已在其他地方犯同樣的錯誤在節目中,例如if (position !=c); - 請注意,C中的分號不僅僅是用於美化效果 - 分號分號(或分號丟失)可以顯着改變程序的行爲。

+3

令人印象深刻的趕上! – 2012-03-06 15:09:41

+1

同樣適用於'if(position!= c);' – Lucas 2012-03-06 15:11:16

+1

非常感謝!我一直在俯視這個!我做了一個混亂! – user1046219 2012-03-06 15:41:13