본문 바로가기
기타

[C] txt파일로 학생의 성적 평균과 석차 구하기

by 돌맹96 2023. 6. 18.
728x90
반응형

무작위로 학생 성적 데이터 생성하기 (tistory.com)

 

무작위로 학생 성적 데이터 생성하기

프로젝트를 진행하다가 무작위 40명의 학생이름, 국어성적, 영어성적, 수학성적으로된 txt파일을 생성해야했다. 임의로 작성하려면 시간이 너무걸려서 파이썬 코드로 한번 짜봤다. import time import

sdm6410.tistory.com

오늘은 생성된 데이터를 가지고 한번 C로 성적의 평균과 석차를 구해보자.

 

파일의 구조는 읽는 함수 : read.c

총점과 평균을 구하는 함수 : grade.c

석차 함수 : rank.c (알고리즘은 quick sort 알고리즘을 이용)

구현한 코드는 다음과 같다.

main.c

#include <stdio.h>
#include "read.h"
#include "grade.h"
#include "rank.h"

#define SIZE 40

int main() {
    char names[SIZE][20];
    int kor[SIZE], math[SIZE], eng[SIZE];
    int total[SIZE], rank[SIZE];
    float average[SIZE];

    readFile("score.txt", names, kor, math, eng, SIZE);
    calculateGrade(kor, math, eng, total, average, SIZE);
    calculateRank(total, rank, SIZE);

    printf("이름\t국어\t수학\t영어\t총점\t평균\t석차\n");
    for (int i = 0; i < SIZE; i++) {
        printf("%s\t%d\t%d\t%d\t%d\t%.2f\t%d\n", names[i], kor[i], math[i], eng[i], total[i], average[i], rank[i]);
    }

    return 0;
}

grade.c

void calculateGrade(const int kor[], const int math[], const int eng[], int total[], float average[], int size) {
    for (int i = 0; i < size; i++) {
        total[i] = kor[i] + math[i] + eng[i];
        average[i] = (float)total[i] / 3;
    }
}

grade.h

#ifndef GRADE_H
#define GRADE_H

void calculateGrade(const int kor[], const int math[], const int eng[], int total[], float average[], int size);

#endif

rank.c

#include <stdio.h>
#include <stdlib.h>
void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int partition(int scores[], int low, int high) {
    int pivot = scores[high];
    int i = low - 1;

    for (int j = low; j < high; j++) {
        if (scores[j] > pivot) {
            i++;
            swap(&scores[i], &scores[j]);
        }
    }

    swap(&scores[i + 1], &scores[high]);
    return i + 1;
}

void quickSort(int scores[], int low, int high) {
    if (low < high) {
        int pi = partition(scores, low, high);

        quickSort(scores, low, pi - 1);
        quickSort(scores, pi + 1, high);
    }
}

void calculateRank(const int total[], int rank[], const int size) {
    int* sortedTotal = malloc(size * sizeof(int));
    if (sortedTotal == NULL) {
        printf("메모리 할당 오류\n");
        return;
    }

    for (int i = 0; i < size; i++) {
        sortedTotal[i] = total[i];
    }

    quickSort(sortedTotal, 0, size - 1);

    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            if (total[i] == sortedTotal[j]) {
                rank[i] = j + 1;
                break;
            }
        }
    }

    free(sortedTotal);
}

rank.h

#pragma once
#ifndef RANK_H
#define RANK_H

void calculateRank(const int total[], int rank[], int size);

#endif

read.c

#include <stdio.h>


void readFile(const char* filename, char names[][20], int kor[], int math[], int eng[], int size) {
    FILE* file;
    fopen_s(&file, filename, "r");
    if (file == NULL) {
        printf("파일을 열 수 없습니다.\n");
        return;
    }

    for (int i = 0; i < size; i++) {
        fscanf_s(file, "%s %d %d %d", names[i], sizeof(names[i]), &kor[i], &math[i], &eng[i]);
    }

    fclose(file);
}

read.h

#pragma once
#ifndef READ_H
#define READ_H

void readFile(const char* filename, char names[][20], int kor[], int math[], int eng[], int size);

#endif

파일 구조
결과화면

궁금하신점있으면 댓글 환영입니다.

728x90
반응형