2013-04-17 16 views
0

我正在研究一個程序,該程序將用於對學生測試分數進行排序並最終檢索分數的均值,中位數和模式。由於一些奇怪的原因,我的泡泡排序不工作..我不確定爲什麼。如果語句沒有執行,氣泡排序根本不起作用

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#define N 3 

int main (void) 
{ 

char vStudents[N][15], trans = 'y', vTemp2; 
int vScores[N], vTemp, x, i = 0, j=0, NewN; 

printf("\t\tWhatsamatta U Scores System\n\n"); 

do 
{ 
    printf("Please Enter Students Name: "); 
    gets(vStudents[i]); 
    trans = 'N'; 
    while (trans == 'N') 
    { 
     printf("Enter Students Score: "); 
     scanf("%d", &vScores[i]); 
     fflush(stdin); 

     if (vScores[i] >= 0 & vScores[i] <= 100) 
      trans = 'y'; 
     else 
      printf("Score is invalid, please re-enter score.\n"); 
    } 
    i++; 
    j++; 
} while (j != N); 


for(x = 0; x < N - 1; x++) 
{ 
    if ((x < N - 1) && (vScores[i] > vScores[i + 1])) 
    { 
     vTemp = vScores[i]; 
     vScores[i] = vScores[i + 1]; 
     vScores[i + 1] = vTemp; 
     x = -1; 
    } 
} 

printf("%d %d %d\n\n", vScores[0], vScores[1], vScores[2]); 

system("Pause"); 
return 0; 

任何幫助將是有用的,在此先感謝!

+1

由於您使用visual studio,您是否嘗試過visual studio的非常好的調試器來逐行檢查並檢查變量? – Patashu

+0

是的,我已經嘗試過,但調試器跳過了冒泡排序的部分。它顯示for循環的開始,但直接跳到底部的printf。 – user2084990

+1

調試器不會說謊。這意味着你的for循環根本沒有被執行。也許第一次執行for循環的條件是錯誤的。 – Patashu

回答

4

至少有一個錯誤:

for(x = 0; x < vScores[N] - 1; x++) 
{ 
    if ((x < vScores[N] - 1) && (vScores[N] > vScores[N + 1])) 
    { 

應該

for(x = 0; x <N - 1; x++) 
{ 
    if ((x < N - 1) && (vScores[N] > vScores[N + 1])) 
    { 
    //^^you should not compare index x with array elements 
1

N是永遠3.如果我們在你的代碼替換3 N,它還有意義?

for(x = 0; x < vScores[3] - 1; x++) 
{ 
    if ((x < vScores[3] - 1) && (vScores[3] > vScores[3 + 1])) 
    { 
     vTemp = vScores[3]; 
     vScores[3] = vScores[3 + 1]; 
     vScores[3 + 1] = vTemp; 
     x = -1; 
    } 
} 

好了,現在它是這樣的:

for(x = 0; x < N - 1; x++) 
{ 
    if ((x < N - 1) && (vScores[i] > vScores[i + 1])) 
    { 
     vTemp = vScores[i]; 
     vScores[i] = vScores[i + 1]; 
     vScores[i + 1] = vTemp; 
     x = -1; 
    } 
} 

詢問,什麼時候i變化?

+0

謝謝!我已經完成了,可能是5或6分鐘前,但泡泡排序仍然沒有執行..我想我應該更新代碼真正快速 – user2084990