zoukankan      html  css  js  c++  java
  • 学生关灯的问题

    教室里有编号为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);

  • 相关阅读:
    报错apachectl restart
    报错apachectl -t
    LAMP 1.6 Discuz安装
    LAMP 1.4 PHP编译安装
    LAMP 1.2 Apache编译安装
    java时间操作
    URL参数中文乱码解决
    python | mongodb 常用命令
    python | Linux的上的MongoDB的安装与卸载
    python | 对 Flask 蓝图(Blueprint)的理解
  • 原文地址:https://www.cnblogs.com/batman425/p/3333081.html
Copyright © 2011-2022 走看看