C Primer Plus 第六版(中文版)第十四章(14.18.5)编程练习答案

#include 
#include 
#include 
#include 

void set_students(struct student ar[], int n);
void find_averages(struct student ar[], int n);
void show_messages(const struct student ar[], int n);
void show_averages(const struct student ar[], int n);

#define LEN 10
#define	CSIZE 4
#define SCORES 3

struct name
{
	char fname[LEN];
	char lname[LEN];
};

struct student
{
	struct name mes;
	float grade[SCORES];
	float aver;
};


int main()
{

	struct student classes[CSIZE] = 
	{
		{"Flip", "Snide"},
		{"Clare", "Voyans"},
		{"Bingo", "Higgs"},
		{"Fawn", "Hunter"}

	};

	set_students(classes, CSIZE);

	find_averages(classes, CSIZE);
	show_messages(classes, CSIZE);
	show_averages(classes, CSIZE);
		


	return 0;
}

void set_students(struct student ar[], int n)
{
	int i, j;

	for (i = 0; i < n; i ++) //4个学生
	{
		printf("请为%s %s输入三个成绩:\n",ar[i].mes.fname, ar[i].mes.lname);

		for (j =0; j < SCORES; j ++)//一个学生三个成绩,后面计算平均数
		{
			while ( scanf_s ("%f\n", &ar[i].grade[j]) != 1)//1为真
			{
				while (getchar() != '\n')//其余的输入算是乱码,要被处理掉
					continue;
				printf("输入无效,重新输入:");
			}
		}
	}

	return;
}

void find_averages(struct student ar[], int n)//数组作为参数传递,“.”去指向结构体里的数据
{
	int i,j;
	float sum;

	for (i = 0; i < n; i++)
	{
		for (j = 0, sum = 0.0f; j < SCORES; j++)//开始计算平均数,上面已经让输入了
		{
			sum += ar[i].grade[j];
		}
		ar[i].aver = sum / SCORES;
	}
	return;
}

void show_messages(const struct student ar[], int n)
{
	int i, j;

	for (i = 0; i < n; i++)
	{
		printf("\n%s %s的三科成绩是:", ar[i].mes.fname, ar[i].mes.lname);//结构体的嵌套
		for (j = 0; j < SCORES; j ++)
		{
			printf("%g",ar[i].grade[j]);
		}
		printf("\n平均分是:%g", ar[i].aver);


	}
	return;
}
void show_averages(const struct student ar[], int n)
{
	int i;
	float total;

	for (i = 0, total = 0.0f;i < n; i++)
	{
		total += ar[i].aver;
	}
	printf("\n班级平均分", total/n);
	return;
}

你可能感兴趣的:(C,Primer,Plus课后题练习,c语言)