您的位置:首页 > 编程语言 > C语言/C++

C语言基础练习14

2017-11-10 23:50 357 查看
1.有3个学生的信息,放在结构体数组中,要求输出全部学生的信息

#include "stdafx.h"
#include<stdio.h>

struct Student
{
int num;
char name[20];
char sex;
int age;
};
struct Student stu[3] = { {10101,"Li Lin",'M',18},{10102,"Zhang Fang",'M',19},{10104,"Wang Min",'F',20} };

int main()
{
struct Student *p;
printf(" No. Name sex age\n");
for (p = stu; p < stu + 3; p++)
printf("%5d %-20s %2c %4d\n", p->num, p->name, p->sex, p->age);
return 0;
}运行结果:



2.写一函数建立一个有3名学生数据的单向动态链表并输出链表

#include "stdafx.h"
#include<stdio.h>
#include<malloc.h>
#define LEN sizeof(struct Student)
struct Student
{
long num;
float score;
struct Student*next;
};
int n;
struct Student*creat()
{
struct Student*head;
struct Student*p1, *p2;
n = 0;
p1 = p2 = (struct Student*) malloc(LEN);
scanf_s("%ld,%f", &p1->num, &p1->score);
head = NULL;
while (p1->num != 0)
{
n = n + 1;
if (n == 1)head = p1;
else p2->next = p1;
p2 = p1;
p1 = (struct Student*) malloc(LEN);
scanf_s("%ld,%f", &p1->num, &p1->score);
}
p2->next = NULL;
return(head);
}

void print(struct Student* head)
{
struct Student * p;
printf("\nNow,These %d records are:\n", n);
p = head;
if(head!=NULL)
do
{
printf("%ld %5.1f\n", p->num, p->score);
p = p->next;
} while (p != NULL);
}

int main()
{
struct Student*head;
head = creat();
print(head);
}
运行结果:



3.有若干个人员的数据,其中有学生和老师。学生的数据包括:姓名、号码、性别、职业、班级。教师的数据包括:姓名、号码、性别、职业、职务。要求用同一个表格来处理

#include "stdafx.h"
#include<stdio.h>
struct
{
int num;
char name;
char sex;
char job;
union
{
int clas;
char position;
}category;
}person[2];

int main()
{
int i;
for (i = 0; i < 2; i++)
{
printf("please enter the data of person:\n");
scanf_s("%d %c %c %c", &person[i].num, &person[i].name, &person[i].sex, &person[i].job);
if (person[i].job == 's')
scanf_s("%d", &person[i].category.clas);
else if (person[i].job == 't')
scanf_s("%c", &person[i].category.position);
else
printf("Input error!");
}
printf("\n");
printf("No. name sex job class/position\n");
for (i = 0; i < 2; i++)
{
if (person[i].job == 's')
printf("%-6d%-10c%-4c%-4c%-10d\n", person[i].num, person[i].name, person[i].sex, person[i].job, person[i].category.clas);
else
printf("%-6d%-10c%-4c%-4c%-10c\n", person[i].num, person[i].name, person[i].sex, person[i].job, person[i].category.position);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 练习