编写程序,能从键盘输入一批学生的成绩(以负数为结束标志),计算平均分,并统计不及格成绩的个数
时间: 2024-11-24 10:40:30 浏览: 36
当你需要编写一个C语言程序来完成这个任务时,你可以遵循以下步骤:
1. 首先,定义一个结构体来存储学生信息,包括姓名和成绩。例如:
```c
typedef struct {
char name[50];
int score;
} Student;
```
2. 定义一个变量来存储总分数和不及格的学生数量,初始化为0。
```c
int total_score = 0, fail_count = 0;
```
3. 使用`while`循环来读取用户的输入直到遇到负数。在循环里,你可以使用`scanf`函数获取输入的分数并更新计数器。
```c
while (1) {
printf("Enter student's name and score (negative number to exit): ");
fgets(student.name, sizeof(student.name), stdin);
if (sscanf(student.name, "%s %d", student.name, &student.score) != 2 || student.score < 0) {
break; // 如果输入了负数或不符合格式,退出循环
}
total_score += student.score;
if (student.score <= 60) { // 这里假设及格线为60分
fail_count++;
}
}
```
4. 计算平均分,除以学生人数(但请注意,因为没有处理所有可能的错误情况,如非整数输入,所以这里直接用总分除以1)。
```c
int num_students = fail_count + 1; // 注意加上最后一个已读取到的学生
double average_score = (total_score == 0) ? 0 : (double)total_score / num_students;
```
5. 打印结果:
```c
printf("Average score: %.2f\n", average_score);
printf("Number of students with a failing grade: %d\n", fail_count);
```
完整的代码示例:
```c
#include <stdio.h>
#include <string.h>
typedef struct {
char name[50];
int score;
} Student;
int main() {
int total_score = 0, fail_count = 0;
Student current_student;
while (1) {
printf("Enter student's name and score (negative number to exit): ");
fgets(current_student.name, sizeof(current_student.name), stdin);
if (sscanf(current_student.name, "%s %d", current_student.name, ¤t_student.score) != 2 || current_student.score < 0) {
break;
}
total_score += current_student.score;
if (current_student.score <= 60) {
fail_count++;
}
}
int num_students = fail_count + 1;
double average_score = (total_score == 0) ? 0 : (double)total_score / num_students;
printf("Average score: %.2f\n", average_score);
printf("Number of students with a failing grade: %d\n", fail_count);
return 0;
}
```
阅读全文