初识联合类型小练习

#include <iostream>
using namespace std;
struct Line
{
	double x1, x2, y1, y2;
};
struct Rectangle
{
	double left, right, top, bottom;
};
struct Circle
{
	double x, y, r;
};
union Figure
{
	Line line;
	Rectangle rectangle;
	Circle circle;
};
enum Shape { LINE, RECTANGLE, CIRCLE };
struct TaggedFigure
{
	Shape shape;
	Figure figure;
};
void input(TaggedFigure[], int);
void draw(TaggedFigure);

void draw_line(Line);
void draw_rectangle(Rectangle);
void draw_circle(Circle);

int main()
{
	const int N = 100;
	TaggedFigure figures[N];
	input(figures, N);
	for (int i = 0; i < N; i++)
		draw(figures[i]);
	return 0;
}
void input(TaggedFigure figures[], int n)
{
	for (int i = 0; i < n; i++)
	{
		int shape;
		cout << "请输入要绘制的图形(0:线段;1:矩形;2:圆形; -1:结束):";
		cin >> shape;
		if (shape == -1)
			break;
		switch (shape)
		{
		case 0:
			figures[i].shape = LINE;
			cout << "请输入线段的起点和终点坐标(x1, y1, x2, y2):" << endl;
			cin >> figures[i].figure.line.x1
				>> figures[i].figure.line.x2
				>> figures[i].figure.line.y1
				>> figures[i].figure.line.y2;
			break;
		case 1:
			figures[i].shape = RECTANGLE;
			cout << "请输入矩形的左上角和右下角的坐标(left, top, right, bottom):" << endl;
			cin >> figures[i].figure.rectangle.left
				>> figures[i].figure.rectangle.top
				>> figures[i].figure.rectangle.right
				>> figures[i].figure.rectangle.bottom;
			break;
		case 2:
			figures[i].shape = CIRCLE;
			cout << "请输入圆心坐标和半径(x, y ,r):" << endl;
			cin >> figures[i].figure.circle.x
				>> figures[i].figure.circle.y
				>> figures[i].figure.circle.r;
			break;
		}
	}
}

void draw(TaggedFigure figures)
{
	switch (figures.shape)
	{
	case LINE:
		draw_line(figures.figure.line);
		break;
	case RECTANGLE:
		draw_rectangle(figures.figure.rectangle);
		break;
	case CIRCLE:
		draw_circle(figures.figure.circle);
		break;
	}
}
//上述的程序中为给出draw_line、draw_rectangle以及draw_circle三个函数的实现。
参考:《程序设计教程》(陈家骏、郑滔编著)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值