编写程序,定义教师信息的结构体类型,成员包括工资卡号、姓名、性别、出生年月(年/月)、婚姻状态(未婚/已婚/离异,采用共用体类型表示)以及工作部门等。输入教师信息并输出。
时间: 2023-06-23 13:10:14 浏览: 164
以下是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef union {
char unmarried[3];
char married[3];
char divorced[3];
} Marriage;
typedef struct {
int salaryNo;
char name[20];
char gender;
struct {
int year;
int month;
} birth;
Marriage marriageStatus;
char department[20];
} Teacher;
int main() {
Teacher teacher;
printf("请输入工资卡号:");
scanf("%d", &teacher.salaryNo);
printf("请输入姓名:");
scanf("%s", teacher.name);
printf("请输入性别:");
scanf(" %c", &teacher.gender); // 注意空格
printf("请输入出生年月(例如 1990 5):");
scanf("%d %d", &teacher.birth.year, &teacher.birth.month);
printf("请输入婚姻状态(1:未婚,2:已婚,3:离异):");
int status;
scanf("%d", &status);
switch (status) {
case 1:
teacher.marriageStatus.unmarried[0] = '未';
teacher.marriageStatus.unmarried[1] = '婚';
teacher.marriageStatus.unmarried[2] = '\0';
break;
case 2:
teacher.marriageStatus.married[0] = '已';
teacher.marriageStatus.married[1] = '婚';
teacher.marriageStatus.married[2] = '\0';
break;
case 3:
teacher.marriageStatus.divorced[0] = '离';
teacher.marriageStatus.divorced[1] = '异';
teacher.marriageStatus.divorced[2] = '\0';
break;
default:
printf("无效的婚姻状态!\n");
exit(1);
}
printf("请输入工作部门:");
scanf("%s", teacher.department);
printf("\n教师信息如下:\n");
printf("工资卡号:%d\n", teacher.salaryNo);
printf("姓名:%s\n", teacher.name);
printf("性别:%c\n", teacher.gender);
printf("出生年月:%d年%d月\n", teacher.birth.year, teacher.birth.month);
printf("婚姻状态:%s\n", teacher.marriageStatus.unmarried); // 共用体只能同时存储一个成员
printf("工作部门:%s\n", teacher.department);
return 0;
}
```
我们定义了一个 `Marriage` 共用体类型来表示婚姻状态,用 `union` 关键字定义。在输入时,根据用户输入的数字判断婚姻状态,并将对应的字符串赋值给共用体的成员。注意,共用体只能同时存储一个成员,所以最后输出时我们只能输出 `unmarried` 成员。
在 `main()` 函数中,首先定义一个 `Teacher` 结构体类型的变量 `teacher`,然后依次输入工资卡号、姓名、性别、出生年月、婚姻状态和工作部门,并输出教师信息。
阅读全文