欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

利用EASYX库做的约瑟夫环演示

程序员文章站 2024-03-18 10:08:52
...

运行代码时需要先安装EASYX库!!!

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<graphics.h>      
#include<conio.h>
#include<math.h>
#define PI 3.1415926
using namespace std;

char str[10000];

int R = 250;
int R1 = 320;

typedef struct node
{
	int num;
	int x;
	int y;
	int r;
	node *next;
}node, *link;

link create_link(int n);
void drew_circle(node* head, int n, int m);

int main()
{
	int n, m;
	cout << "请输入总人数n和报数值m" << endl;
	cin >> n >> m;
	initgraph(720, 720);
	setorigin(360, 360);
	setfillcolor(BLUE);
	settextcolor(WHITE);
	drew_circle(create_link(n), n, m);
	return 0;
}

node* create_link(int n)
{
	node *p, *q;
	p = (node*)malloc(sizeof(node));
	p->next = NULL;
	p->next = p;
	p->r = 50;
	for (int i = 1; i <= n; i++)
	{
		q = (node*)malloc(sizeof(node));
		q->num = i;

		q->r = 50;
		q->x = cos(360.0 / n * (i - 1) / 180 * PI)*R;
		q->y = -1 * sin(360.0 / n * (i - 1) / 180 * PI)*R;
		q->next = p->next;
		p->next = q;
	}
	return p;
}

void print_word(int n)
{
	node *p1, *q1;
	p1 = (node*)malloc(sizeof(node));
	p1->next = NULL;
	p1->next = p1;
	for (int i = 1; i <= n; i++)
	{
		q1 = (node*)malloc(sizeof(node));
		q1->num = i;
		q1->x = cos(360.0 / n * (i - 1) / 180 * PI)*R1;
		q1->y = -1 * sin(360.0 / n * (i - 1) / 180 * PI)*R1;
		q1->next = p1->next;
		p1->next = q1;
	}
	p1 = p1->next;
	for (int i = 0; i < n; i++)
	{
		TCHAR b[100];
		_stprintf(b, _T("%d"), p1->num);
		outtextxy(p1->x, p1->y, b);
		p1 = p1->next;
	}
}

void drew_circle(node* z, int n, int m)
{
	node*p = z;
	int j = 0;

	while (p->next != z)
	{
		j++;
		p = p->next;
	}

	//删除头结点
	node *q = p->next;
	p->next = q->next;
	free(q);

	while (1)
	{
		for (int i = 0; i < j; i++)//打印圆
		{
			fillcircle(p->x, p->y, p->r);
			p = p->next;
		}

		print_word(n);//打印圆编号

		for (int i = 0; i < m - 1; i++) //移动到删除节点位置		
		{
			p = p->next;

			setfillcolor(YELLOW);
			fillcircle(p->x, p->y, p->r);
			Sleep(500);
			setfillcolor(BLUE);
			fillcircle(p->x, p->y, p->r);
		}
		if (j == 1)//生成结果
		{
			TCHAR s[] = _T("最后一个圆的位置是");
			TCHAR a[100];
			outtextxy(0, 0, s);
			_stprintf(a, _T("%d"), p->num);
			outtextxy(0,20, a);
			system("pause");
		}

		//删除节点
		node *q = p->next;
		p->next = q->next;
		free(q);
		j--;

		Sleep(500);
		getbkcolor();
		cleardevice();
	}
}

利用EASYX库做的约瑟夫环演示

相关标签: c++