C语言写一个菜单,首先从文件score.txt中读取数字成绩,功能1为将读取到的数字成绩转换为等级ABCDE并保存在另一个文件grade.txt中,功能二为统计不同等级的人数,功能三为输出读取到的成绩,写出代码并画出带符号的数据流图
时间: 2024-05-30 12:15:32 浏览: 131
代码如下:
#include <stdio.h>
#define MAX_SIZE 100
void convert_to_grade(char score[], char grade[]) {
int i;
for (i = 0; score[i] != '\0'; i++) {
if (score[i] >= '90') {
grade[i] = 'A';
} else if (score[i] >= '80') {
grade[i] = 'B';
} else if (score[i] >= '70') {
grade[i] = 'C';
} else if (score[i] >= '60') {
grade[i] = 'D';
} else {
grade[i] = 'E';
}
}
grade[i] = '\0';
}
void count_grades(char grade[], int count[]) {
int i;
for (i = 0; grade[i] != '\0'; i++) {
switch (grade[i]) {
case 'A':
count[0]++;
break;
case 'B':
count[1]++;
break;
case 'C':
count[2]++;
break;
case 'D':
count[3]++;
break;
case 'E':
count[4]++;
break;
}
}
}
void print_scores(char score[]) {
printf("Scores: %s\n", score);
}
void print_grades(char grade[]) {
printf("Grades: %s\n", grade);
}
void print_counts(int count[]) {
printf("A: %d\n", count[0]);
printf("B: %d\n", count[1]);
printf("C: %d\n", count[2]);
printf("D: %d\n", count[3]);
printf("E: %d\n", count[4]);
}
int main() {
FILE *score_file, *grade_file;
char score[MAX_SIZE], grade[MAX_SIZE];
int count[5] = {0, 0, 0, 0, 0};
int choice;
score_file = fopen("score.txt", "r");
if (score_file == NULL) {
printf("Error: cannot open file.\n");
return 1;
}
fgets(score, MAX_SIZE, score_file);
fclose(score_file);
printf("Menu:\n");
printf("1. Convert to grades and save to file.\n");
printf("2. Count grades.\n");
printf("3. Print scores.\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
convert_to_grade(score, grade);
grade_file = fopen("grade.txt", "w");
if (grade_file == NULL) {
printf("Error: cannot open file.\n");
return 1;
}
fprintf(grade_file, "%s", grade);
fclose(grade_file);
printf("Grades saved to file.\n");
break;
case 2:
convert_to_grade(score, grade);
count_grades(grade, count);
print_counts(count);
break;
case 3:
print_scores(score);
break;
default:
printf("Invalid choice.\n");
return 1;
}
return 0;
}
符号流图如下:
![image.png](attachment:image.png)
阅读全文