head.h
#ifndef __HEAD_H__
#define __HEAD_H__
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[20];
int age;
char sex;
char job;
union {
float score;
char post[20];
};
}person_t;
person_t *get_space(int n);
void input(person_t *p,int n);
void output(person_t *p,int n);
float avg_stu(person_t *p,int n);
int teacher_count(person_t *p,int n);
#endif
main.c
#include "head.h"
int main(int argc, const char *argv[])
{
person_t *person;
int n;
printf("请输入录入人员数量:");
scanf("%d", &n);
person=get_space(n);
input(person,n);
output(person,n);
printf("学生平均成绩:%f\n", avg_stu(person,n));
printf("老师人数:%d\n", teacher_count(person,n));
//释放空间
free(person);
person=NULL;
return 0;
}
head.c
#include "head.h"
int main(int argc, const char *argv[])
{
person_t *person;
int n;
printf("请输入录入人员数量:");
scanf("%d", &n);
person=get_space(n);
input(person,n);
output(person,n);
printf("学生平均成绩:%f\n", avg_stu(person,n));
printf("老师人数:%d\n", teacher_count(person,n));
//释放空间
free(person);
person=NULL;
return 0;
}
linux@linux:~/test/5.15$ cat head.c
#include "head.h"
//申请空间
person_t *get_space(int n){
person_t *p=(person_t *)malloc(sizeof(person_t)*n);
return p;
}
//循环录入学校人员信息
void input(person_t *p,int n){
int i;
for(i=0;i<n;i++){
printf("请输入人员姓名:");
scanf("%s", (p+i)->name);
printf("请输入人员年龄:");
scanf("%d", &(p+i)->age);
printf("请输入人员性别:");
scanf(" %c", &(p+i)->sex);
printf("请输入人员职务s/t:");
scanf(" %c", &(p+i)->job);
if((p+i)->job=='s'||(p+i)->job=='S'){
printf("请输入人员成绩:");
scanf("%f", &(p+i)->score);
}else if((p+i)->job=='t'||(p+i)->job=='T'){
printf("请输入人员职位:");
scanf("%s", (p+i)->post);
}else{
printf("输入错误\n");
}
}
}
//循环输出学校人员信息
void output(person_t *p,int n){
int i;
printf("姓名\t年龄\t性别\t职务\t成绩\\职位\n");
for(i=0;i<n;i++){
if((p+i)->job=='s'||(p+i)->job=='S')
printf("%s\t%d\t%c\t%c\t%f\n", (p+i)->name,(p+i)->age,(p+i)->sex,(p+i)->job,(p+i)->score);
else if((p+i)->job=='t'||(p+i)->job=='T')
printf("%s\t%d\t%c\t%c\t%s\n", (p+i)->name,(p+i)->age,(p+i)->sex,(p+i)->job,(p+i)->post);
}
}
//计算学生平均成绩
float avg_stu(person_t *p,int n){
int i,count=0;
float avg_sum=0;
for(i=0;i<n;i++){
if((p+i)->job=='s'||(p+i)->job=='S'){
avg_sum+=(p+i)->score;
count++;
}
}
return avg_sum/count;
}
//计算老师个数
int teacher_count(person_t *p,int n){
int i,count=0;
for(i=0;i<n;i++){
if((p+i)->job=='t'||(p+i)->job=='T'){
count++;
}
}
return count;
}