面向对象程序设计.txt

来自「钱能主编 C++程序设计教程(第一版) 该书习题的答案代码」· 文本 代码 · 共 120 行

TXT
120
字号
//********************************
//**          Jose3.cpp         **
//**       (third edition)      **
//********************************
#include <iostream.h>
#include <iomanip.h>

struct Jose
{
	int code;
	Jose* next;
};

//global vars
int n;             //num of childs  
int begin;         //start position
int m;             //the counting interval
Jose* pivot;       //the guard of linked list
Jose* pCur;        //pointer of current node

//declaration of fuctions
int assign();
void initial(Jose* pBoys);
void count(int m);
void process();

//main
void main()
{
	if(!assign())
	{
		cout<<"The program failed."<<endl;
		return;
	}

	Jose* pJose=new Jose[n];
	initial(pJose);
	count(begin-1);
	process();

	cout<<endl<<"the winner is "<<pCur->code<<endl;

	delete []pJose;
}

//initialize
int assign()
{
	int number,start,count;
	cout<<"please input the number,begin,count:"<<endl;
	cin>>number>>start>>count;

	//check the inputs
	if(number<2)
	{
		cerr<<"bad number of boys."<<endl;
		return 0;
	}
	if(start<1)
	{
		cerr<<"bad begin position."<<endl;
		return 0;
	}
	if(count<1||count>number)
	{
		cerr<<"bad interval number."<<endl;
		return 0;
	}

	n=number;begin=start;m=count;
	return 1;
}

//initialize the linked list
void initial(Jose* pJose)
{
	int l=0;
	Jose* px=pJose;
	cout<<"initialize the linked list."<<endl;

	for(int i=1;i<=n;i++)
	{
		px->next=pJose+i%n;
		px->code=i;
		px=px->next;

		if((l++ % 10)==0)
			cout<<endl;
		cout<<setw(4)<<i;
	}
	cout<<endl;
	pCur=pJose+n-1;
}

//count m childs
void count(int m)
{
	for(int i=0;i<m;i++)
	{
		pivot=pCur;
		pCur=pivot->next;
	}
}

//process all the child before the winner chosed
void process()
{
	int l=0;
	for(int i=1;i<n-1;i++)
	{
		count(m);

		if((l++ % 10)==0)
			cout<<endl;
		cout<<setw(4)<<pCur->code;

		pivot->next=pCur->next;
		pCur=pivot;
	}
}

⌨️ 快捷键说明

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