用c语言:班上有30人,每人有学号,数学,英语,c语言3门课程的成绩数据。编程完成如下任务: 1、将数据输入到文本文件score.txt 2、计算每人总分,将学号,数学,英语,c语言,总分等数据按总分从高到低输出每位同学的全部数据。 3、将每位同学的数据按学号顺序计算输出各同学的总分排名,分数最高的名次为1,分数相同的名次相同,若有i个同学排在第x位,则下个分数的名次为x+i位。并将这些数据均写入文本文件newscore.txt
时间: 2023-05-29 17:04:37 浏览: 236
C语言程序设计-输入2个学生3门课的成绩,计算学生成绩平均分,课程平均分和最高分.
5星 · 资源好评率100%
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LEN 20
#define MAX_STU_NUM 30
struct student {
char name[MAX_NAME_LEN];
int id;
int math;
int english;
int c;
int total;
};
int compare(const void* a, const void* b) {
struct student* s1 = (struct student*)a;
struct student* s2 = (struct student*)b;
return s2->total - s1->total;
}
void print_student(struct student* s) {
printf("%s %d %d %d %d %d\n", s->name, s->id, s->math, s->english, s->c, s->total);
}
void write_student(FILE* fp, struct student* s) {
fprintf(fp, "%s %d %d %d %d %d\n", s->name, s->id, s->math, s->english, s->c, s->total);
}
int main() {
struct student students[MAX_STU_NUM];
int i, j, k;
FILE* fp;
char filename[] = "score.txt";
char newfilename[] = "newscore.txt";
// 读入学生数据
for (i = 0; i < MAX_STU_NUM; i++) {
printf("请输入第%d个学生的姓名、学号、数学成绩、英语成绩、C语言成绩,中间以空格分隔:\n", i + 1);
scanf("%s %d %d %d %d", students[i].name, &students[i].id, &students[i].math, &students[i].english, &students[i].c);
students[i].total = students[i].math + students[i].english + students[i].c;
}
// 写入文件
fp = fopen(filename, "w");
if (fp == NULL) {
printf("无法打开文件\n");
return 1;
}
for (i = 0; i < MAX_STU_NUM; i++) {
write_student(fp, &students[i]);
}
fclose(fp);
// 按总分排序并输出
qsort(students, MAX_STU_NUM, sizeof(struct student), compare);
printf("按总分排序后的学生数据:\n");
for (i = 0; i < MAX_STU_NUM; i++) {
print_student(&students[i]);
}
// 按学号顺序计算排名并写入文件
fp = fopen(newfilename, "w");
if (fp == NULL) {
printf("无法打开文件\n");
return 1;
}
fprintf(fp, "学号 总分 排名\n");
for (i = 1; i <= MAX_STU_NUM; i++) {
int rank = 1;
for (j = 0; j < MAX_STU_NUM; j++) {
if (students[j].id == i) {
// 计算排名
for (k = 0; k < j; k++) {
if (students[k].total > students[j].total) {
rank++;
}
}
write_student(fp, &students[j]);
fprintf(fp, "%d %d\n", students[j].id, rank);
break;
}
}
}
fclose(fp);
return 0;
}
阅读全文