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

枚举、结构体、联合体的简单应用程序-C语言

2017-11-08 14:59 351 查看
#include <stdio.h>

//图元的类型
enum SHAPE_TYPE{
RECT_TYPE = 0,
CIRCLE_TYPE = 1,
TRIANGLE_TYPE = 2,
SHAPE_NUM,
};
//为了定义三角形的坐标而设
struct point{
float x;
float y;
};
//创建shape结构体
struct shape{
//int type;
enum SHAPE_TYPE type;
union {
struct {
float x;
float y;
float w;
float h;
}rect;

struct {
float c_x;
float c_y;
float r;
}circle;

struct {
struct point t0;
struct point t1;
struct point t2;
}triangle;
}u;
};
//初始化矩形
void init_rect_shape(struct shape *s, float x, float y, float w, float h)
{
s->type = RECT_TYPE;
s->u.rect.x = x;
s->u.rect.y = y;
s->u.rect.w = w;
s->u.rect.h = h;
return ;
}
//初始化三角形
void init_triangle_shape(struct shape *s,float a, float b, float c, float d,float e, float f)
{
s->type = TRIANGLE_TYPE;
s->u.triangle.t0.x = a;
s->u.triangle.t0.y = b;
s->u.triangle.t1.x = c;
s->u.triangle.t1.y = d;
s->u.triangle.t2.x = e;
s->u.triangle.t2.y = f;
return ;
}
//初始化圆
void init_circle_shape(struct shape *s, float a, float b, float r)
{
s->type = CIRCLE_TYPE;
s->u.circle.c_x = a;
s->u.circle.c_y = b;
s->u.circle.r = r;
return;
}
//输出图形
void draw_shape(struct shape *shapes, int count)
{
int i = 0;
for(i=0;i<count;i++)
{
switch(shapes[i].type)
{
case CIRCLE_TYPE:
printf("circle:%f, %f, %f\n", shapes[i].u.circle.c_x, shapes[i].u.circle.c_y, shapes[i].u.circle.r);
break;
case TRIANGLE_TYPE:
printf("triangle:%f, %f, %f, %f, %f, %f\n", shapes[i].u.triangle.t0.x, shapes[i].u.triangle.t0.y, shapes[i].u.triangle.t1.x, shapes[i].u.triangle.t1.y, shapes[i].u.triangle.t2.x, shapes[i].u.triangle.t2.y);
break;
case RECT_TYPE:
printf("circle:%f, %f, %f, %f\n", shapes[i].u.rect.x, shapes[i].u.rect.y, shapes[i].u.rect.w, shapes[i].u.rect.h);
break;
default:
break;
}
}

return ;
}

int main()
{
struct shape shape_set[3];
init_rect_shape(&shape_set[0], 100, 200, -100, 200);
init_triangle_shape(&shape_set[1], 10, 20, 30, -30, 40, -40);
init_circle_shape(&shape_set[2], 100, 200, 300);
draw_shape(shape_set, 3);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: