用c语言写一个约瑟夫环的问题,就是一群人排成圈报数,然后报到某个倍数的人退出,以此类推,求最后剩下的一个人。
#include
#include
int a[999]={};
int renshu,beishu;
int main(){
printf("请分别输入人数和倍数!\n");
scanf("%d%d",&renshu,&beishu);
int now=1;
int m=renshu;
while(m>1){
for(int n=beishu;n>0;now=now%renshu+1){
if (a[now]==0){
n=n-1;
}
}
a[now]=1;
m=m-1;
now=now%renshu+1;
}
for(int x=1;x
printf("%d",a[x]);
}
return 0;
}
运行结果比如输入20,4则得出0000100001000010000
我感觉没问题,不知道哪里出错了
a[1]到a[renshu]只有一个元素值是0
循环解决方案,代码参考:
#include <stdio.h>
int main () {
int renshu, beishu;
scanf("%d %d", &renshu, &beishu);
int i = 0, j = 1;
int a[999] = {0};
int m = renshu;
while (m > 1) {
if (a[i % renshu] == 0) {
if (j % beishu == 0) {
a[i % renshu]++;
m--;
}
j++;
}
i++;
}
for (int i = 0; i < renshu; i++) {
printf("%d", a[i]);
}
printf("\n");
return 0;
}