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

#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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值