2014-02-13 98 views
0
#include<iostream> 
#include<conio.h> 

using namespace std; 

int main() 
{ 
    int a, b, c[5], d; 

    cout << "enter any five number\n"; 
    for(a=0; a<5; a++) 
    { 
     cin>>c[a]; 
    } 
    for(a=0; a<5; a++) 
    { 
     for(b=++a; b<5; b++) 
     { 
      if(c[b] < c[a]) 
      { 
       d = c[b]; 
       c[b] = c[a]; 
       c[a] = d; 
      } 
     }  
    } 

    cout << "\nhere is the entered numbers in order\n"; 
    for(a=0; a<5; a++) 
    { 
     cout << c[a]; 
     cout << endl; 
    } 
    getch(); 
    return 3; 
} 

我在桌面上檢查這個程序,我希望程序按升序對數字進行排序,但是我得到了錯誤的輸出幫助。排序算法給出錯誤結果

+0

,不,不,不@MarounMaroun我很抱歉,如果它是一個壞習慣,這是我的最後一次。 – samuel

+0

你不能只使用std :: sort嗎? – Ralara

+0

@Ralara:標題的原始格式確實表明這是一項作爲練習指定的任務 – quetzalcoatl

回答

1

在內部循環應該a + 1++a

1

for(a=0;a<5;a++)for(b=++a;..)導致a要遞增兩次。

您的意思是for(b=a+1;b<5;b++)

+0

是的這就是我的意思,但我不知道第二個循環是導致輸出的那一個,非常感謝你@quetzalcoatl – samuel

0
for(a=0; a<5; a++) 
    { 
     for(b=++a; b<5; b++) 
     { 
      if(c[b] < c[a]) 
      { 
       d = c[b]; 
       c[b] = c[a]; 
       c[a] = d; 
      } 
     }  
    } 

這應該是

for(a=0; a<4; a++) 
{ 
    for(b=a+1; b<5; b++) 
    { 
     if(c[b] < c[a]) 
     { 
      d = c[b]; 
      c[b] = c[a]; 
      c[a] = d; 
     } 
    }  
} 
+0

一個<4應該更好,以避免無用的步驟。 – Zodoh

0
for(a=0; a<5-1; a++){ 
    for(b=0; b<5-a-1; b++){ 
    if(c[b] < c[a]){ 
     d = c[b]; 
     c[b] = c[a]; 
     c[a] = d; 
    } 
    } 
}