定义一个用于记录人员信息的结构体,该结构体同时用于记录两类人员信息:学生信息,包括其姓名、编号、职业、成绩;教师信息,包括其姓名、编号、职业、任教科目。分别声明一个记录学生信息和教师信息的结构体变量,取值自定,输出这两个结构体变量中的信息。要求:运用共用体,实现结构体既可以记录学生成绩又可以教师任教科目的要求。
#include <stdio.h>
#include<stdlib.h>
struct student
{
char name[20];
char id[10];
char profession;
union
{
char course[20];
double score;
};
};
int main()
{
int i, n;
printf("how many people you want to input:");
scanf("%d", &n);
struct student* ps;
ps = (struct student*)malloc(n * sizeof(struct student));
printf("Input:\n");
for (i = 0; i < n; i++) {
printf("\tNo. %d\n", i + 1);
printf("\t\tName: ");
scanf("%s", ps[i].name);
printf("\t\tID: ");
scanf("%s", ps[i].id);
getchar(); //有%c时要吃掉
printf("\t\tProfession: ");
scanf("%c", &ps[i].profession);
if (ps[i].profession == 'S') {
printf("\t\tScore: ");
scanf("%d", &ps[i].score);
}
else {
printf("\t\tCourse: ");
scanf("%s", &ps[i].course);
}
}
printf("Output:\n");
for (i = 0; i < n; i++) {
printf("\tNo. %d", i + 1);
printf("\n\t\tName: %s", ps[i].name);
printf("\n\t\tID: %s", ps[i].id);
printf("\n\t\tProfession: %c", ps[i].profession);
if (ps[i].profession == 'S') {
printf("\n\t\tScore: %d\n", ps[i].score);
}
else {
printf("\n\t\tCourse: %s\n", ps[i].course);
}
}
return 0;
}