Сведения о студентах. Массив а отсортировать по ФИО, а массив в по успеваемости - C (СИ)

Узнай цену своей работы

Формулировка задачи:

Здравствуйте. Необходимо создать два массива структур а и в, содержащих сведения о студентах(ФИО, №группы, изучаемые дисциплины, успеваемость). Массив а отсортировать по ФИО, а массив в по успеваемости... вывести полученные данные на экран. В чем ошибка данного кода? помогите с сортировкой, пожалуйсто
#include <stdio.h>
 
const int n=10;
int size=0, razm=0;
 
typedef struct a{
    char FIO[2];
    int Numbgr;
    char Disc[5];
    int Ocen[5];
}strA;
 
strA masA[100];
 
typedef struct b{
    char FIO[2];
    int Numbgr;
    char Disc[5];
    int Ocen[5];
}strB;
 
strB masB[100];
 
void vvodA(int size){
    int j, j;
    printf("Vvedite svedeniya o studentax gruppy A\n\n");
for(j=0; j<size; j++)
    printf("Vvedite FIO\n");
printf("Vvedite familiyu  ");
scanf("%s\n", &masA[j].FIO[0]);
printf("Vvedite inicialy  ");
scanf("%s\n", &masA[j].FIO[1]);
printf("vvedite nomer gruppy: ");
scanf("%d\n", &masA[j].Numbgr);
printf("Vvedite izu4aemye discipliny i ocenki po disciplinam:\n");
for(int i=0; i<5; i++)
{scanf("%s", &masA[j].Disc[i]);
scanf("%d\n", &masA[j].Ocen[i]);
}
}
 
void vvodB(int size){
    int j;
    printf("vvedite svedeniya o studentax gruppy B\n\n");
for(j=0; j<size; j++)
    printf("Vvedite FIO\n");
printf("Vvedite familiyu  ");
scanf("%s\n", &masB[j].FIO[0]);
printf("Vvedite inicialy  ");
scanf("%s\n", &masB[j].FIO[1]);
printf("vvedite nomer gruppy: ");
scanf("%d\n", &masB[j].Numbgr);
printf("Vvedite izu4aemye discipliny i ocenki po disciplinam:\n");
for(int i=0; i<5; i++)
{scanf("%s", &masA[j].Disc[i]);
scanf("%d\n", &masA[j].Ocen[i]);
}
}
 
// сортировка по фамилии
void sortfam(int size){
    char temp;
int i, j, poz;
for(i=0; i<size; ++i);
{
poz=i;
temp=masA[i].FIO[0];
for(j=i+1; j<size; ++j)
{
    if(masA[j].FIO[0]<temp)
    {poz=j;
    temp=masA[j].FIO[0];}
}
masA[poz].FIO[0]=masA[i].FIO[0];
masA[i].FIO[0]=temp;
}
}
 
void vyvod(int size)
{
    for(int i=0; i<size; i++)
    {
    printf("FIO: %s  %s\n", masA[i].FIO[0], masA[i].FIO[1]);
    printf("Nomer gruppy: %d\n", masA[i].Numbgr);
    printf("Discipliny i ocenki:\n");
    for(int j=0; j<5; j++)
    {printf("%s -- %d\n", masA[i].Disc[j], masA[i].Ocen[j]);}
    }
}
 
int main (void)
{
printf("Skolko u4asch4ixsja v gruppe A?");
scanf("%d", &size);
printf("Skolko u4asch4ixsja v gruppe B?");
scanf("%d", &razm);
vvodA(size);
vvodB(razm);
sortfam(size);
vyvod(size);
}

Решение задачи: «Сведения о студентах. Массив а отсортировать по ФИО, а массив в по успеваемости»

textual
Листинг программы
/* ANSI C 99 */
 
#ifndef _ISOC99_SOURCE
#define _ISOC99_SOURCE 1
#endif
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
/* функция для очистки потока ввода */
void flush_input(void) {
    char c;
    
    while ( scanf("%c", &c) == 1 && c != '\n' )
        ;
}
 
/* строки короткие, но 31 символа должно бы на всё хватать... */
typedef char string_t[32];
#define get_string(s) ( scanf("%31[^\n]%*c", (s)) == 1 )
 
/* фамилия, имя, отчество */
typedef struct PERSON {
    string_t surname;
    string_t name;
    string_t patronymic;
} person_t;
 
/* чтение с консоли, 0 - успешно, -1 - не успешно... */
int get_person(person_t * person) {
    printf("Surname: ");
    if ( ! get_string(person->surname) )
        return -1;
    printf("Name: ");
    if ( ! get_string(person->name) )
        return -1;
    printf("Patronymic: ");
    if ( ! get_string(person->patronymic) )
        return -1;
    
    return 0;
}
 
/* оценки, предметы, etc... */
#define MIN_SCORE (1)
#define MAX_SCORE (5)
 
typedef int dscore_t;
typedef const char * dname_t;
 
typedef struct DISCIPLINE {
    dname_t name;
    dscore_t score;
} discipline_t;
 
int get_score(discipline_t * d) {
    int ret;
    
    printf("Discipline %s, score: ", d->name);
    ret = scanf("%d", &(d->score));
    flush_input();
    
    return ( ret == 1 && d->score >= MIN_SCORE && d->score <= MAX_SCORE ) ? 0 : -1;
}
 
#define PREDEFINED_DISCIPLINES_COUNT 3
dname_t PREDEFINED_DISCIPLINE_NAMES[] = { "Metaphysics", "Alchemy", "Chiromancy" };
 
/* собственно студент */
typedef struct STUDENT {
    person_t personData;
    int disciplinesCount;
    discipline_t * disciplineScores;
} student_t;
 
student_t * new_student(void) {
    student_t * s = malloc(sizeof(student_t));
    
    if ( ! s )
        return NULL;
    
    memset(&(s->personData), 0, sizeof(person_t));
    s->disciplinesCount = 0;
    s->disciplineScores = NULL;
    
    return s;
}
 
void kill_student(student_t * s) {
    free(s->disciplineScores);
    free(s);
}
 
int get_predefined_discipline_scores(student_t * s) {
    int i;
    
    s->disciplinesCount = PREDEFINED_DISCIPLINES_COUNT;
    if ( ! ( s->disciplineScores = malloc(sizeof(discipline_t) * s->disciplinesCount) ) )
        return -1;
    
    for ( i = 0; i < PREDEFINED_DISCIPLINES_COUNT; ++i ) {
        s->disciplineScores[i].name = PREDEFINED_DISCIPLINE_NAMES[i];
        if ( get_score(&(s->disciplineScores[i])) )
            return -1;
    }
    
    return 0;
}
 
double average_score(student_t * s) {
    int i;
    dscore_t sum = 0;
    
    for ( i = 0; i < s->disciplinesCount; ++i )
        sum += s->disciplineScores[i].score;
    
    return ((double)sum) / s->disciplinesCount;
}
 
/* 
   Функция печати массива студентов - абсолютно топорная, заточенная под отдельно взятый случай, универсальную писать лень.
   Мало того! единственное место в программе, требующее поддержки компилятором стандарта ANSI C 99 - вызов snprintf() 
   внутри этой функции. Если пользуетесь компилятором, не поддерживающим этот стандарт, просто перепишите вывод
   как-нибудь по-своему...
*/
void print_students_group(student_t ** students, int count) {
    int i;
    string_t buf;
    
    printf("+------------------------------+-------------+---------+------------+---------+\n");
    printf("| Surname N.P.                 | Metaphysics | Alchemy | Chiromancy | Average |\n");
    printf("+------------------------------+-------------+---------+------------+---------+\n");
    
    for ( i = 0; i < count; ++i ) {
        if ( snprintf(buf, sizeof(string_t), "%s %c.%c.", students[i]->personData.surname, students[i]->personData.name[0], students[i]->personData.patronymic[0]) < 0 ) {
            fprintf(stderr, "WARNING! Can't get surname and initials!\n");
            continue;
        }
        printf("| %-28s | %11d | %7d | %10d | %7.1f |\n", buf, students[i]->disciplineScores[0].score, 
                                students[i]->disciplineScores[1].score,
                                students[i]->disciplineScores[2].score,
                                average_score(students[i])
        );
        printf("+------------------------------+-------------+---------+------------+---------+\n");
    }
}
 
/* функции сравнения студентов */
 
int compare_by_name_ascendant(const void * a, const void * b) {
    student_t * sA = *(student_t**)a;
    student_t * sB = *(student_t**)b;
    int ret;
    
    ret = strcmp(sA->personData.surname, sB->personData.surname);
    if ( ! ret )
        ret = strcmp(sA->personData.name, sB->personData.name);
    if ( ! ret )
        ret = strcmp(sA->personData.patronymic, sB->personData.patronymic);
    
    return ret;
}
 
int compare_by_average_score_descendant(const void * a, const void * b) {
    student_t * sA = *(student_t**)a;
    student_t * sB = *(student_t**)b;
    
    double diff = average_score(sA) - average_score(sB);
    
    return ( diff > 0.0 ) ? -1 : ( diff < 0.0 ) ? 1 : 0;
}
 
 
/************************************** MAIN PART OF PROGRAM **************************************/
 
int main(void) {
    student_t ** students;
    int studentsCount, i;
    
    printf("Number of students: ");
    if ( scanf("%d", &studentsCount) != 1 || studentsCount < 1 ) {
        fprintf(stderr, "Wrong input!\n");
        exit(1);
    }
    flush_input();
    
    if ( ! ( students = malloc(sizeof(student_t*) * studentsCount) ) ) {
        fprintf(stderr, "Memory error!\n");
        exit(1);
    }
    
    for ( i = 0; i < studentsCount && printf("\nInformation for student #%d:\n", i + 1); ++i ) {
        if ( ! ( students[i] = new_student() ) || get_person(&(students[i]->personData)) || get_predefined_discipline_scores(students[i]) ) {
            fprintf(stderr, "Fail while creating student #%d\n", i + 1);
            exit(1);
        }
    }
    
    printf("\n\nSorted by name:\n");
    qsort(students, studentsCount, sizeof(student_t*), compare_by_name_ascendant);
    print_students_group(students, studentsCount);
    
    printf("\n\nSorted by average score:\n");
    qsort(students, studentsCount, sizeof(student_t*), compare_by_average_score_descendant);
    print_students_group(students, studentsCount);
    
    for ( i = 0; i < studentsCount; ++i )
        kill_student(students[i]);
    free(students);
    
    exit(0);
}

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

6   голосов , оценка 4 из 5
Похожие ответы