您的位置:首页 > 理论基础 > 数据结构算法

数据结构(C语言版)第一版 习题P37~P38

2015-05-29 08:24 519 查看
T1:

编写一个结构表示太阳系中的行星。

#include<stdio.h>
#include<string.h>

typedef struct{
char name[10];
double distance;
int satellite;
}planet;

void print(planet *);

void main()
{
planet p3,p2,*pt3,*pt2;
strcpy(p3.name,"Earth");
p3.distance = 1.52e8;
p3.satellite = 1;
pt3 = &p3;
print(pt3);

strcpy(p2.name,"Venus");
p2.distance = 1.07e8;
p2.satellite = 0;
pt2 = &p2;
print(pt2);
}

void print(planet *p)
{
printf("Name: %s\n",p->name);
printf("distance: %g\n",p->distance);
printf("Satellite: %d\n",p->satellite);
}


T2.修改humanbeing结构体

#include<stdio.h>
#include<string.h>

typedef struct{
int month;
int day;
int year;
}date;

typedef struct {;}nomarriage;
typedef struct{date dom,dodivorce;}divorce;
typedef struct{date dom,dadeath;}widow;
typedef struct{
enum tagfiled{single,married,widowed,dovorced} status;
union{
nomarriage nom;
date dom;
divorce divorcestuff;
widow widowstuff;
}u;
} maritalStatus;

typedef struct {
char name[10];
int age;
float salary;
date dob;
maritalStatus ms;
}humanBeing;

void printPerson(humanBeing *);

int main()
{
humanBeing p1,*pt1;
p1.dob.month = 5;
p1.dob.day = 16;
p1.dob.year = 1978;
strcpy(p1.name, "Fiona");
p1.salary = 1.00;
p1.ms.status = married;
p1.ms.u.dom.month = 10;
p1.ms.u.dom.day = 31;
p1.ms.u.dom.year = 1999;
pt1 = &p1;
printPerson(pt1);
}

void printPerson(humanBeing *p)//使用指针能够节省空间
{/*print out the information on a person */
printf("Name: %s\n", p->name);
printf("DOB: %d/%d/%d\n", p->dob.month, p->dob.day, p->dob.year);
printf("Salary: %5.2f\n", p->salary);//指向结构体的指针只能用->访问成员
switch(p->ms.status){
case married:
printf("Marriage Date: %d/%d/%d\n", p->ms.u.dom.month, p->ms.u.dom.day, p->ms.u.dom.year);
}
}


T3.编写结构表示下列各个形状:三角形,矩形,圆形。

#include <stdio.h>
#include <string.h>

typedef struct {double length, width;} rectStuff;
typedef struct {double base, height;} triStuff;

typedef struct {
char name[10];
enum tagField {rectangle, triangle, circle} shapeType;
union {
rectStuff rect;
triStuff tri;
double radius;
} stats;
}shape;

void printShape(shape);

int main()
{
shape s1, s2, s3;
strcpy(s1.name, "rectangle");
s1.shapeType = rectangle;
s1.stats.rect.length = 10;
s1.stats.rect.width = 20;
strcpy(s2.name, "triangle");
s2.shapeType = triangle;
s2.stats.tri.base = 102;
s2.stats.tri.height = 450;
strcpy(s3.name ,"circle");
s3.stats.radius = 2.5;
/*  printf("%f\n",s3.stats.radius);*/
printShape(s1);
printShape(s2);
printShape(s3);

}

void printShape(shape s)
{/*print out the information on a shape */
printf("Name: %s\n", s.name);
switch(s.shapeType){
case rectangle:
printf("\tLength:%f\n", s.stats.rect.length);
printf("\tWidth:%f\n\n", s.stats.rect.width);
break;
case triangle:
printf("\tBase:%f\n", s.stats.tri.base);
printf("\tHeight:%f\n\n", s.stats.tri.height);
break;
case circle:
printf("Radius:%f\n",s.stats.radius);
break;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: