关于约瑟夫环的有关问题,求教
关于约瑟夫环的问题,求教。
本学期有C++程序设计课程设计这门课。第3章要求设计菜单选择趣味程序中,有一段是设计约瑟夫环的一种出圈游戏,按书中提供的程序例子,运行的时候会出错,就是显示完第一个出圈人的名字之后就提示出错,不能运行。实在不解,希望各位指点。
#include"cpp3.h"
void Joseph(SeqList c[],int length)
{
int m,i;
cout<<"Please input first interval m(m<=20):";
cin>>m;
while (m>20)
{
cout<<"It's too large.Please input another number:";
cin>>m;
}
cout<<"Please input code:"<<endl;
getchar();
char s[10];
for(i=0;i<length;i++)
{
cout<<"第"<<i+1<<"个人的名字:";
gets_s(s);
c[i].SetName(s);
}
i=-1;
int j,k;
for (k=1;k<=length;k++)
{
j=0;
while (j<m)
{
i++;
if (i==length)
i=0;
if (c[i].GetNum()!=0) j++;
}
if(k==length) break;
c[i].DispName();
cout<<",";
c[i].SetName(0);
}
c[i].DispName();
cout<<endl;
}
void game1()
{
const int n=30;
int length=0;
cout<<"Please input the number of people:";
cin>>length;
SeqList c[n];
for(int i=0;i<length;i++)
{
c[i].SetNum(i+1);
c[i].SetName(" ");
}
Joseph(c,length);
}
------解决方案--------------------
本学期有C++程序设计课程设计这门课。第3章要求设计菜单选择趣味程序中,有一段是设计约瑟夫环的一种出圈游戏,按书中提供的程序例子,运行的时候会出错,就是显示完第一个出圈人的名字之后就提示出错,不能运行。实在不解,希望各位指点。
#include"cpp3.h"
void Joseph(SeqList c[],int length)
{
int m,i;
cout<<"Please input first interval m(m<=20):";
cin>>m;
while (m>20)
{
cout<<"It's too large.Please input another number:";
cin>>m;
}
cout<<"Please input code:"<<endl;
getchar();
char s[10];
for(i=0;i<length;i++)
{
cout<<"第"<<i+1<<"个人的名字:";
gets_s(s);
c[i].SetName(s);
}
i=-1;
int j,k;
for (k=1;k<=length;k++)
{
j=0;
while (j<m)
{
i++;
if (i==length)
i=0;
if (c[i].GetNum()!=0) j++;
}
if(k==length) break;
c[i].DispName();
cout<<",";
c[i].SetName(0);
}
c[i].DispName();
cout<<endl;
}
void game1()
{
const int n=30;
int length=0;
cout<<"Please input the number of people:";
cin>>length;
SeqList c[n];
for(int i=0;i<length;i++)
{
c[i].SetNum(i+1);
c[i].SetName(" ");
}
Joseph(c,length);
}
------解决方案--------------------
- C/C++ code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
/* 结构体和函数声明 */
typedef struct _node_t
{
int n_num;
struct _node_t *next;
} node_t;
node_t *node_t_create(int n);
node_t *node_t_get(node_t **pn, int m);
/* 功能函数实现 */
/*
* name: node_t_create
* params:
* n [in] 输入要构造的链表的个数
* return:
* 返回构造成功的环形单向链表指针
* notes:
* 构造节点数量为 n 的环形单向链表
*
*/
node_t * node_t_create(int n)
{
node_t *p_ret = NULL;
if (0 != n)
{
int n_idx = 1;
node_t *p_node = NULL;
/* 构造 n 个 node_t */
p_node = (node_t *) malloc(n * sizeof(node_t));
if (NULL == p_node)
return NULL;
else
memset(p_node, 0, n * sizeof(node_t));
/* 内存空间申请成功 */
p_ret = p_node;
for (; n_idx < n; n_idx++)
{
p_node->n_num = n_idx;
p_node->next = p_node + 1;
p_node = p_node->next;
}
p_node->n_num = n;
p_node->next = p_ret;
}
return p_ret;
}
/*
* name: main
* params:
* none
* return:
* int
* notes:
* main function
*/
int main()
{
int n, m;
node_t *p_list, *p_iter;
n = 20; m = 6;
/* 构造环形单向链表 */
p_list = node_t_create(n);
/* Josephus 循环取数 */
p_iter = p_list;
m %= n;
while (p_iter != p_iter->next)
{
int i = 1;
/* 取到第 m-1 个节点 */
for (; i < m - 1; i++)
{
p_iter = p_iter->next;