josephus.cpp

来自「面向对象的作业」· C++ 代码 · 共 78 行

CPP
78
字号
#include <iostream.h>
#include <iomanip.h>
#include "jose.h"
#include "ring.h"

Ring::Ring(int n)
{
	pBegin=new Boy[n];
	pCurrent=pBegin;
	for (int i=1; i<=n; i++, pCurrent=pCurrent->next)
	{
		pCurrent->next=pBegin+i%n;
		pCurrent->code=i;
		PutBoy();
	}
	cout<<endl;
	pCurrent=&pBegin[n-1];
}

void Ring::Count(int m)
{
	for (int i=0; i<m; i++)
	{
		pivot=pCurrent;
		pCurrent=pivot->next;
	}
}

void Ring::PutBoy()
{
	static int numInLine;
	if (numInLine++%10==0) cout<<endl;
	cout<<setw(4)<<pCurrent->code;
}

void Ring::ClearBoy()
{
	pivot->next=pCurrent->next;
	pCurrent=pivot;
}

Ring::~Ring()
{
	delete[] pBegin;
}

void Jose::Initial()
{
	int num,m;
	cout<<"Please input the number of boys and interval per count:";
	cin>>num>>m;
	numOfBoys=num;
	beginPos=1;
	interval=m;
}

void Jose::GetWinner()
{
	Ring x(numOfBoys);
	x.Count(beginPos);
	for (int i=1; i<numOfBoys; i++)
	{
		x.Count(interval);
		x.PutBoy();
		x.ClearBoy();
	}
	cout<<"\nThe winner is:";
	x.PutBoy();
}

void main()
{
	Jose jose;
	jose.Initial();
	jose.GetWinner();
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?