这题用链表有点麻烦了,其实没有必要,因为就是固定的3个数据。不如用数组省事。
但既然有要求,那就用吧。
#include <stdio.h>
#include <stdlib.h>
#define NUM 3
/* 定义工资结构体 */
typedef struct {
int base;
int bonus;
int patch;
}s_salary;
/* 定义生日结构体 */
typedef struct {
int year;
int month;
int day;
}s_birthday;
/* 定义老师信息结构体 */
typedef struct s_teacher {
char no[10];
char name[10];
char title[10];
s_salary salary;
s_birthday birthday;
struct s_teacher *next;
}s_teacher;
void main ()
{
s_teacher head, *teacher, *last;
int i, total;
/* 获取输入数据 */
last = &head;
for (i=0; i<NUM; i++)
{
teacher = malloc(sizeof(s_teacher));
if (teacher == NULL)
{
printf("memory error\n");
exit;
}
last->next = teacher;
scanf("%s %s %s %d %d %d %d %d %d",
teacher->no, teacher->name, teacher->title,
&teacher->salary.base, &teacher->salary.bonus, &teacher->salary.patch,
&teacher->birthday.year, &teacher->birthday.month, &teacher->birthday.day);
teacher->next = NULL;
last = teacher;
}
/* 输出所有工资大于5000的教师信息 */
last = &head;
for (i=0; i<NUM; i++)
{
teacher = last->next;
total = teacher->salary.base + teacher->salary.bonus + teacher->salary.patch;
if (total > 5000)
{
printf("姓名: %s, 出生日期:%d.%d.%d, 工资:%d\n",
teacher->name, teacher->birthday.year,
teacher->birthday.month, teacher->birthday.day,
total);
}
last = teacher;
}
/* 释放所分配的内存 */
teacher = head.next;
for (i=0; i<NUM; i++)
{
last = teacher;
teacher = last->next;
free(last);
}
}
运行结果:
![](https://video.ask-data.xyz/img.php?b=https://iknow-pic.cdn.bcebos.com/b7003af33a87e9507655c8fd1d385343faf2b4e4?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_600%2Ch_800%2Climit_1%2Fquality%2Cq_85%2Fformat%2Cf_auto)
追问采纳了,谢谢大佬,能不能麻烦把数组的也发一下😃谢谢谢谢
追答不用链表,直接定义一个数组,大致结构不变,但省去了分配内存和释放内存的步骤:
#include <stdio.h>
#include <stdlib.h>
#define NUM 3
/* 定义工资结构体 */
typedef struct {
int base;
int bonus;
int patch;
}s_salary;
/* 定义生日结构体 */
typedef struct {
int year;
int month;
int day;
}s_birthday;
/* 定义老师信息结构体 */
typedef struct s_teacher {
char no[10];
char name[10];
char title[10];
s_salary salary;
s_birthday birthday;
// struct s_teacher *next; //数组不需要定义链表的指针
}s_teacher;
void main ()
{
s_teacher teacher[NUM]; // 定义这么多的结构数组就行了
int i, total;
/* 获取输入数据 */
for (i=0; i<NUM; i++)
{
scanf("%s %s %s %d %d %d %d %d %d",
teacher[i].no, teacher[i].name, teacher[i].title,
&teacher[i].salary.base, &teacher[i].salary.bonus, &teacher[i].salary.patch,
&teacher[i].birthday.year, &teacher[i].birthday.month, &teacher[i].birthday.day);
}
/* 输出所有工资大于5000的教师信息 */
for (i=0; i<NUM; i++)
{
total = teacher[i].salary.base + teacher[i].salary.bonus + teacher[i].salary.patch;
if (total > 5000)
{
printf("姓名: %s, 出生日期:%d.%d.%d, 工资:%d\n",
teacher[i].name, teacher[i].birthday.year,
teacher[i].birthday.month, teacher[i].birthday.day,
total);
}
}
}本回答被提问者采纳