I can not sort the notes with the use of struct

0

I want to sort the student's grades, but I can not do it because when I receive the grades I'm using the index j, I think that's the problem, but I do not know how to solve it.

 #include<stdio.h>
 #include<stdlib.h>

double ordena(double *a, double *b);

struct notas
{
  double notas[3];
  char nome[100];
};


int main(void)
{
  int i, j;
  struct notas aluno[2];
  for(i = 0; i < 2; i++)
  {
    printf("Informe os nomes dos alunos :");
    scanf("%s", aluno[i].nome);
    system("cls");
    for(j = 0; j < 3; j++)
    {
        printf("Informe as notas do aluno %d:", j + 1);
        scanf("%lf", &aluno[i].notas[j]);
        system("cls");
    }
    system("cls");
   }
   for(i = 0; i < 2; i++)
   {
      for(j = i + 1; j < 3; j++)
       {
        ordena(&aluno[i].notas[j], &aluno[j].notas[j]);
       }
   }
   for(i = 0; i < 2; i++)
    {
      printf("Nome dos alunos %s:", aluno[i].nome);
       for(i = 0; i < 3; i++)
       {
        printf("%.2lf\n", aluno[i].notas[j]);
       }
  }
  system("pause");
  return 0;
}

double ordena(double *a, double *b)
{
  double o;
  if(*a > *b)
  {
    o = *a;
    *a = *b;
    *b = o;
  }
   return 0;
}
    
asked by anonymous 02.01.2018 / 21:55

1 answer

0

The function orders you wrote does nothing more than the exchange of elements. The right thing would be to do the ordering within the function. Ex:

void ordena(double vet[]) {
    int i, j;
    double aux;

    for (i = 1; i < 3; i++) {
        aux = vet[i];

        for (j = i - 1; (j >= 0) && (aux < vet[j]); j--) {
            vet[j + 1] = vet[j];
        }

        vet[j+1] = aux;
    }
}

To sort just call:

for(i = 0; i < 2; i++){
   ordena(alunos[i].notas);
}

And at the time of displaying the values you are using the variable 'i' in 2 different for loops in the same scope. The right thing would be like this:

for(i = 0; i < 2; i++){
     printf("Nome dos alunos %s:", alunos[i].nome);
     for(j = 0; j < 3; j++) {
        printf("%.2lf\n", alunos[i].notas[j]);
     }
}

And just to finish avoid always declaring variables with the same name as the struct in which it belongs, otherwise your code will be difficult to read. What I suggest is that instead of 'notes', declare the struct with the name 'Students' as it stores information about the students.

    
03.01.2018 / 01:50