一道有趣的C程序,请各位高手来分析一下,其中错在哪里?
题目:有n个人围成一圈,顺序排号.从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问到最后留下的是原来第几号的那位.
程序:
#include <iostream>
#include <math.h>
#define nmax 50;
void main()
{
int i,k,m,n,num[50],*p;
printf( "Please input the total of numbers: ");
scanf( "%d ",& n);
p=num;
for(i=0;i <n;++i)
*(p+i)=i+1;
i=0;
k=0;
m=0;
while (m <n-1)
{
if(*(p+i)!=0)
k++;
if(k=3)
{
*(p+i)=0;
k=0;
m++;
}
i++;
if(i==n)i=0;
}
while(*p==0)
p++;
printf( "%d is left\n ",*p);
}
[解决办法]
1、开头应该包含头文件stdio.h
2、if(k=3) //应该为if(k==3)
{
*(p+i)=0;
k=0;
m++;
}
[解决办法]
#include <iostream>
#include <math.h>
#define max 100
void main()
{
int i,j,k,n;
int a[max];
printf( "input the number: \n ");
while(scanf( "%d ",&n) == 1)
{
if(n> max)
{
printf( "input the number lessthan max:\n ");
scanf( "%d ",&n);
}
for(i=1;i <=n;i++)
{
a[i]=1;
}
k=0;
i=1;
j=1;
while(k <n)
{
if(j <3 || a[i]==0)
{j+=a[i];i++;}
else
{
a[i]=0;
printf( "%d\t ",i);
k++;
j=1;
i++;
}
if(i> n)
i=1;
}
printf( "\n ");
printf( "input the next number: \n ");
}
}
[解决办法]
约瑟夫环嘛 前几天刚写的c语言版
#include <stdio.h>
#include <stdlib.h>
struct lnode
{
int id;
struct lnode *next;
};
int main()
{
int m,n;
struct lnode *head=NULL;
struct lnode *creat(int n);
void select(struct lnode *head,int m);
/*void select(struct lnode *head,int m);*//*测试循环链表是否正确*/
printf( "please input the total number:\n ");
scanf( "%d ",&n);
head=creat(n);
printf( "please input the cycle number:\n ");
scanf( "%d ",&m);
select(head,m);
getchar();
getchar();
return 0;
}
struct lnode *creat(int n)
{
struct lnode *head=NULL,*p=NULL,*q=NULL;
head-> next=NULL;
while(n!=0)
{
p=(struct lnode *)malloc(sizeof(struct lnode));
p-> id=n;
if(!p)
{
printf( "error!\n ");
exit (0);
}
if(head-> next==NULL)
{
q=head-> next=p;
p-> next=NULL;
}
else
{
p-> next=head-> next;
head-> next=p;
}
n--;
}
q-> next=head-> next;
return head-> next;
}
/*建立链表*/
/*void select(struct lnode *head,int m)
{
int n=m;
struct lnode *p=head;
while(n!=0)
{
printf( "%d\n ",p-> id);
p=p-> next;
n--;
}
}
*/
void select(struct lnode *head,int m)
{
struct lnode *q,*p;
int a;
p=head;
while(p!=p-> next)
{
for(a=m;0 <a;a--)
p=p-> next;
q=p-> next;
printf( "selected id is:%d\n ",q-> id);
p-> next=q-> next;
p=p-> next;
free(q);
}
}
/*循环输出*/