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

  1 #include <stdio.h>
  2 
  3 //图元的类型
  4 enum SHAPE_TYPE{
  5     RECT_TYPE = 0,
  6     CIRCLE_TYPE = 1,
  7     TRIANGLE_TYPE = 2,
  8     SHAPE_NUM,
  9 };
 10 //为了定义三角形的坐标而设
 11 struct point{
 12     float x;
 13     float y;
 14 };
 15 //创建shape结构体
 16 struct shape{
 17     //int type;
 18     enum SHAPE_TYPE type;
 19     union {
 20         struct {
 21             float x;
 22             float y;
 23             float w;
 24             float h;
 25         }rect;
 26 
 27         struct {
 28             float c_x;
 29             float c_y;
 30             float r;
 31         }circle;
 32 
 33         struct {
 34             struct point t0;
 35             struct point t1;
 36             struct point t2;
 37         }triangle;
 38     }u;
 39 };
 40 //初始化矩形
 41 void init_rect_shape(struct shape *s, float x, float y, float w, float h)
 42 {
 43     s->type = RECT_TYPE;
 44     s->u.rect.x = x;
 45     s->u.rect.y = y;
 46     s->u.rect.w = w;
 47     s->u.rect.h = h;
 48     return ;
 49 }
 50 //初始化三角形
 51 void init_triangle_shape(struct shape *s,float a, float b, float c, float d,float e, float f)
 52 {
 53     s->type = TRIANGLE_TYPE;
 54     s->u.triangle.t0.x = a;
 55     s->u.triangle.t0.y = b;
 56     s->u.triangle.t1.x = c;
 57     s->u.triangle.t1.y = d;
 58     s->u.triangle.t2.x = e;
 59     s->u.triangle.t2.y = f;
 60     return ;
 61 }
 62 //初始化圆
 63 void init_circle_shape(struct shape *s, float a, float b, float r)
 64 {
 65     s->type = CIRCLE_TYPE;
 66     s->u.circle.c_x = a;
 67     s->u.circle.c_y = b;
 68     s->u.circle.r = r;
 69     return;
 70 }
 71 //输出图形
 72 void draw_shape(struct shape *shapes, int count)
 73 {
 74     int i = 0;
 75     for(i=0;i<count;i++)
 76     {
 77         switch(shapes[i].type)
 78         {
 79             case CIRCLE_TYPE:
 80                 printf("circle:%f, %f, %f\n", shapes[i].u.circle.c_x, shapes[i].u.circle.c_y, shapes[i].u.circle.r);
 81                 break;
 82             case TRIANGLE_TYPE:
 83                 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);
 84                 break;
 85             case RECT_TYPE:
 86                 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);
 87                 break;
 88             default:
 89                 break;
 90         }
 91     }
 92 
 93     return ;
 94 }
 95 
 96 int main()
 97 {
 98     struct shape shape_set[3];
 99     init_rect_shape(&shape_set[0], 100, 200, -100, 200);
100     init_triangle_shape(&shape_set[1], 10, 20, 30, -30, 40, -40);
101     init_circle_shape(&shape_set[2], 100, 200, 300);
102     draw_shape(shape_set, 3);
103 
104     return 0;
105 }

 

posted @ 2017-11-08 14:57  子雅陌曦  阅读(318)  评论(0编辑  收藏  举报