C Primer Plus 第十四章 编程练习5

作者在 2013-05-16 14:06:18 发布以下内容
/*
写一个程序,满足下列要求:
A. 外部定义一个name结构模板,它含有2个成员:
	一个字符串用于存放名字,另一个字符串用于存放姓氏
B. 外部定义一个student结构模板,它含有3个成员:
	一个name结构,一个存放3个浮点数分数的grade数组,以及一个存放这3个分数平均分的变量
C. 使 main()函数声明一个具有CSIZE(CSIZE = 4)个student结构的数组,
	并随意初始化这些结构的名字部分.使用函数来执行d , e, f, g 部分所描述的任务. 

D. 请求用户输入学生姓名和分数,以交互地获取每个学生的成绩.
	将分数放到相应结构的grade数组成员中 
	您可以自主选择在main()或一个函数中实现这个循环. 
E. 为每个结构计算平均分,并把这个值赋给适合的成员 
F. 输出每个结构中的信息.
G. 输出结构的每个数值成员的班级平均分. 
*/
/*
[CSIZE] ={
		{"Baby's", "Breath"},
		{"Morning", "Glory"},
		{"Ashley", "Jessica"},
		{"Sarah", "Megan"}
	};
*/
#include <stdio.h>
#include <stdlib.h>
#define NAMELEN 11
#define CSIZE 4

struct name{
	char firstname[NAMELEN];
	char lastname[NAMELEN];
};
struct student{
	struct name fullname;
	float grade[3];
	float average;
};
void clearcache(void);
int getinfo(struct student []);
void calc_average(struct student [], const int);
void putinfo(struct student [], const int);

int main(void)
{
	struct student st[CSIZE];
	int count;
	
	count = getinfo(st);
	if(count)
	{
		calc_average(st, count);
		putinfo(st, count);
	}
	else
	{
		printf("No data.");
	}
	puts("Bye.");
	return 0;
}

int getinfo(struct student st[])
{
	int count = 0;
	printf("please enter student info.\n");
	printf("Press [enter] at the start of a line to stop.\n");
	printf("Now enter the firstname: ");
	while(count < CSIZE && 
		  gets(st[count].fullname.firstname) != NULL && 
		  st[count].fullname.firstname[0] != '\0')
	{
		printf("Now enter the lastname: ");
		gets(st[count].fullname.lastname);
		printf("Now enter the first grade: ");
		scanf("%f", &st[count].grade[0]);
		printf("Now enter the second grade: ");
		scanf("%f", &st[count].grade[1]);
		printf("Now enter the third grade: ");
		scanf("%f", &st[count].grade[2]);
		
		if(count < CSIZE)
		{
			printf("Enter next student info.\n");
			printf("Press [enter] at the start of a line to stop.\n");
			printf("Now enter the firstname: ");
		}
		clearcache();
		count++;
	}
	
	return count;
}

void calc_average(struct student st[], const int count)
{
	int i;
	
	for(i = 0; i < count; i++)
	{
		st[i].average = (st[i].grade[0] + st[i].grade[1] + st[i].grade[2]) / 3;
	}
}

void putinfo(struct student st[], const int count)
{
	int i;
	
	printf("The student info list :\n");
	for(i = 0; i < count; i++)
	{
		printf("%s %s :\n",
			st[i].fullname.firstname, st[i].fullname.lastname);
		printf("grade1   grade2   grade3   average\n");
		printf("%6.1f   %6.1f   %6.1f   %7.1f\n", st[i].grade[0], 
			st[i].grade[1], st[i].grade[2], st[i].average);
	}
}
void clearcache(void)
{
	while(getchar() != '\n')
		continue;
}
文章评论,共0条
游客请输入验证码
浏览39548次