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;

任何帮助都会很有用,在此先感谢!

4

2 回答 2

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
于 2013-04-17T23:56:28.887 回答
1

N 始终为 3。如果我们将代码中的 N 替换为 3,它仍然有意义吗?

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改?

于 2013-04-18T00:22:59.747 回答