如果语句没有执行,冒泡排序根本不起作用

时间:2013-04-17 23:53:21

标签: c visual-studio-2010

我正在研究一项计划,该计划将用于对学生的考试成绩进行排序,并最终检索分数的均值,中位数和模式。由于一些奇怪的原因,我的泡泡排序不起作用..我不确定为什么。

#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;

任何帮助都会有用,提前谢谢!

2 个答案:

答案 0 :(得分: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 :(得分: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何时更改?