用C语言编写一个程序,满足有10个学生,每个学生的数据包括学号、姓名、3门功课的成绩。从键盘输入10个学生的数据,要求按平均成绩降序显示出所有学生的数据(包括学号、姓名、3门课成绩、平均成绩),并将其写入文本文件resultxt中。
时间: 2023-12-10 18:42:37 浏览: 68
以下是用C语言编写的程序,可以实现上述要求:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENTS 10
#define MAX_NAME_LENGTH 20
typedef struct {
int id;
char name[MAX_NAME_LENGTH];
int scores[3];
double average;
} Student;
void input_students(Student students[]);
void calculate_averages(Student students[]);
void sort_students(Student students[]);
void output_to_file(Student students[]);
int main() {
Student students[MAX_STUDENTS];
input_students(students);
calculate_averages(students);
sort_students(students);
output_to_file(students);
return 0;
}
void input_students(Student students[]) {
printf("Please enter data for %d students:\n", MAX_STUDENTS);
for (int i = 0; i < MAX_STUDENTS; i++) {
printf("Student %d:\n", i+1);
printf(" ID: ");
scanf("%d", &students[i].id);
printf(" Name: ");
scanf("%s", students[i].name);
for (int j = 0; j < 3; j++) {
printf(" Score %d: ", j+1);
scanf("%d", &students[i].scores[j]);
}
}
}
void calculate_averages(Student students[]) {
for (int i = 0; i < MAX_STUDENTS; i++) {
double sum = 0.0;
for (int j = 0; j < 3; j++) {
sum += students[i].scores[j];
}
students[i].average = sum / 3.0;
}
}
void sort_students(Student students[]) {
for (int i = 0; i < MAX_STUDENTS-1; i++) {
for (int j = i+1; j < MAX_STUDENTS; j++) {
if (students[j].average > students[i].average) {
Student temp = students[i];
students[i] = students[j];
students[j] = temp;
}
}
}
}
void output_to_file(Student students[]) {
FILE *fp = fopen("result.txt", "w");
if (fp == NULL) {
printf("Error: cannot open file\n");
exit(1);
}
fprintf(fp, "ID\tName\tScore 1\tScore 2\tScore 3\tAverage\n");
for (int i = 0; i < MAX_STUDENTS; i++) {
fprintf(fp, "%d\t%s\t%d\t%d\t%d\t%.2f\n", students[i].id, students[i].name,
students[i].scores[0], students[i].scores[1], students[i].scores[2], students[i].average);
}
fclose(fp);
printf("Data saved to result.txt\n");
}
```
该程序使用了一个 `Student` 结构体来存储每个学生的数据,其中包括学号、姓名、3门功课的成绩和平均成绩。程序首先调用 `input_students` 函数从键盘输入每个学生的数据,然后调用 `calculate_averages` 函数计算每个学生的平均成绩,最后调用 `sort_students` 函数按平均成绩降序排序所有学生,并将结果输出到文件中。
阅读全文