学生关灯的问题

教室里有编号为1~50的电灯50盏,现全部处于关闭状态。六(一)班则好有50名同学,现依次进入教室,第一个同学将所有电灯都拉一下,第二个同学将编号为2的倍数的电灯各拉一下,第三个同学将编号为3的倍数的电灯各拉一下……,依此类推,直到最后一个同学操作完毕后,教室里共有几盏灯是亮着的?

首先想到的是定义一个结构体

typedef struct student
{
 int a;
 bool flag;
};

第一种实现方式 结构体数组

 struct student st[50];
 int i,j=1,m;
 for (i=0;i<50;i++)
 {
  st[i].a=i+1;
  st[i].flag=true;
 }
 
 for (i=0;i<50;i++)
 {
  if (st[i].flag==true)
  printf("%d ",st[i].a);
  if (j==10)
  {
   j=0;
   printf(" ");
  }
  j++;
 }
 for(m=2;m<=50;m++)
 {
  for (i=1;i<=50;i++)
  {
  if (i%m==0)
  {
            if (st[i-1].flag==true)
     st[i-1].flag=false;
   else
     st[i-1].flag=true;
  }
  if (j==10)
  {
   j=0;
  }
  j++;
  }
 for (i=0;i<50;i++)
 {
  if (st[i].flag==true)
   printf("%d ",st[i].a);
  if (j==10)
  {
   j=0;
   printf(" ");
  }
  j++;
 }
 }

第二种方式

 typedef struct student
{
 int a[50];
 int flag[50];
};

struct student *st;
 int i,j;
 //初始化操作
 st=(struct student*)malloc(sizeof(struct student));
 for (i=0;i<50;i++)
 {
       st->a[i]=i+1;
    st->flag[i]=0;//0灯全部熄灭
 }
 //50个学生轮流关灯
 for (i=1;i<=50;i++)
  for(j=1;j<=50;j++)
     {
      if (j%i==0)
      {
    if(st->flag[j-1]==0)
           st->flag[j-1]=1;
    else
                    st->flag[j-1]=0;
      }
     }
 //打印亮着的灯
 for (i=0;i<50;i++)
  if (st->flag[i]==1)
           printf("%d ",st->a[i]);
    free(st);

原文地址:https://www.cnblogs.com/batman425/p/3333081.html