数据结构实验3(结构体共用体初尝试)

定义一个用于记录人员信息的结构体,该结构体同时用于记录两类人员信息:学生信息,包括其姓名、编号、职业、成绩;教师信息,包括其姓名、编号、职业、任教科目。分别声明一个记录学生信息和教师信息的结构体变量,取值自定,输出这两个结构体变量中的信息。要求:运用共用体,实现结构体既可以记录学生成绩又可以教师任教科目的要求。

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值