gpt4 book ai didi

c - 使用结构数组的学生信息数据库(C语言)

转载 作者:太空宇宙 更新时间:2023-11-04 01:06:16 25 4
gpt4 key购买 nike

函数 computeScore() 用于使用结构数组创建最多包含 50 名学生的数据库。该函数接收学生、姓名、考试成绩和考试成绩,计算总分,然后打印出来。当学生姓名为“END”时,输入将结束。之后,程序将计算所有学生的总平均分并打印出来。

当我输入第一个学生的信息时它工作正常,但是当程序第二次进入 while 循环时(当我想输入第二个学生的信息时)我遇到了麻烦。

这是我到目前为止所做的:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <math.h>

struct student{
char name[20]; /* student name */
double testScore; /* test score */
double examScore; /* exam score */
double total; /* total score = test+exam scores */
};

void computeScore();

int main()
{
computeScore();
return 0;
}

void computeScore()
{
struct student info[50];
int count = 1;
double allStudent = 0, allStudentAvg;

while (info[count].name != 'END')
{
printf("\nEnter student name: ");
gets(info[count].name);
printf("Enter test score: ");
scanf("%lf", &info[count].testScore);
printf("Enter exam score: ");
scanf("%lf", &info[count].examScore);

info[count].total = (info[count].testScore + info[count].examScore) / 2;
printf("Student %s's total= %f\n", info[count].name, info[count].total);

allStudent += info[count].total;
count++;
}
allStudentAvg = allStudent / count;
printf("Overall average = %f", allStudentAvg);
}

预期输出:

Enter student name: John Doe
Enter test score: 34
Enter exam score: 46
Student John Doe's total = 40.000000

Enter student name: Jane Doe
Enter test score: 60
Enter exam score: 80
Student John Doe's total = 70.000000

Enter student name: END
Overall average: 55.000000

我得到的输出是:

Enter student name: John Doe
Enter test score: 34
Enter exam score: 46
Student John Doe's total = 40.000000

Enter student name: Enter test score:

\\Program skipped the input of 2nd student name

最佳答案

这是因为最后一次调用 scanf,换行符仍在缓冲区中,因此下一个 gets 读取该换行符。

您可以使用虚拟 gets 调用显式获取该换行符,但更容易告诉 scanf 通过在格式:

scanf("%lf ", &info[count].examScore);
/* ^ */
/* | */
/* Note space here */

不要担心前导空格(比如前一个 scanf 调用留在缓冲区中的换行符),因为数字格式(和其他一些格式)会自动跳过前导空格。您可能想阅读 this reference .

关于c - 使用结构数组的学生信息数据库(C语言),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22529571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com