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

来源:互联网 发布:二级数据库程序设计类 编辑:程序博客网 时间:2024/06/04 20:11
#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;}

原创粉丝点击