14.12 设有以下结构类型说明:
struct stud
{
char num[5],name[10];
int s[4];
double ave;
};
请编写:
( 1 )函数 readrec 把 30 名学生的学号、姓名、四项成绩以及平均分放在一个结构
体数组中,学生的学号、姓名和四项成绩由键盘输入,然后计算平均分放
在结构体对应的域中。
( 2 )函数 writerec 输出 30 名学生的记录。
( 3 ) main 函数调用 readrec 函数和 writerec 函数,实现全部程序功能(注:不允
许使用全局变量,函数之间的数据全部使用参数传递)。
※程序如下※
#include <stdio.h>
#define STUDNUM 30
struct stud
{
char num[5],name[10];
int s[4];
double ave;
};
void readrec(struct stud *pStud, int num)
{
int i;
printf("\tNum\tName\tS1\tS2\tS3\tS4\n");
for (i=0; i<num; i++)
{
printf("%d:\t",i);
scanf("%s%s%d%d%d%d",pStud->num,pStud->name,&(pStud->s[0]),
&(pStud->s[1]),&(pStud->s[2]),&(pStud->s[3]));
pStud->ave=(pStud->s[0]+pStud->s[1]+pStud->s[2]+pStud->s[3])/4.0;
pStud++;
}
}
void writerec(struct stud *pStud, int num)
{
int i;
printf("\tNum\tName\tS1\tS2\tS3\tS4\n");
for (i=0; i<num; i++)
{
printf("%d:",i);
printf("\t%s\t%s\t%d\t%d\t%d\t%d\t%lf\n",pStud->num,pStud->name,
pStud->s[0],pStud->s[1],pStud->s[2],pStud->s[3],pStud->ave);
pStud++;
}
}
void main()
{
struct stud student[STUDNUM];
readrec(student,STUDNUM);
writerec(student,STUDNUM);
}
——————————————————————————————————————
14.13 已知 head 指向一个带头节点的单向链表,链表中每个节点包含数据区域( data )
和指针域( next ),数据域为整型。请分别编写函数,在链表中查找数据域值
最大的节点。
※程序如下※
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *SearchMax(struct node *head)
{
int max;
struct node *pMaxNode,*pNode;
pNode = head;
pMaxNode = NULL;
while (pNode != NULL)
{
if (pNode->data > max || pMaxNode == NULL)
{
max = pNode->data;
pMaxNode = pNode;
}
pNode = pNode->next;
}
return pMaxNode;
}
void main()
{
struct node *head,*tail,*pNode;
int data;
printf("Please input data\nEnter 'Exit' to quit.\n");
head = tail = NULL;
while(scanf("%d",&data) > 0)
{
pNode = (struct node*)malloc(sizeof(struct node));
pNode->data = data;
pNode->next = NULL;
if (head == NULL)
head = tail = pNode;
else
{
tail->next = pNode;
tail = pNode;
}
}
if (head != NULL)
printf("Maxnimum data is %d\n", SearchMax(head)->data);
while(head != NULL)
{
pNode = head;
head = head->next;
free(pNode);
}
}