zoukankan      html  css  js  c++  java
  • 3月10日 循环 嵌套 穷举 迭代

    穷举:

    把所有可能的情况都走一遍,使用if条件筛选出来满足条件的情况;

    //单位发了一张150元的购物卡,到超市买洗发水、香皂、牙刷;
                //洗发水15元,香皂2元,牙刷5元;
                //求刚好花完150元,有多少种买法;
                //每种买法都是各买几样;
                //设洗发水x   150/15==10
                //牙刷y      150/5==30
                //香皂z      150/2==75
                int biao = 0;
                int sum = 0;
                for (int x=0;x<=10 ; x++)
                {
                    for (int y = 0;y<=30 ; y++)
                    {
                        for (int z=0;z<=75 ;z++ )
                        {
                            sum++;
                        if(15*x+5*y+2*z==150)
                        {
                            biao++;
                            Console.WriteLine("这是第"+biao+"种买法:洗发水"+x+"瓶,牙刷"+y+"支,香皂"+z+"块。");
                        }
                        }
                    }
    
                }
                Console.WriteLine("共有"+biao+"种买法");
                Console.WriteLine(sum);
                Console.ReadLine();

    迭代:

    从初始情况按照规律不断求解中间情况,最终推导出结果。

     //纸张可以无限次对折,纸张厚度为0.07毫米;
                //问多少次对折后,可以超过8848;
                int a = 7;
                int i = 1;
                for (; ; )
                {
                    a *= 2;
                    if(a>=884800000)
                    {
                        Console.WriteLine(i);
                        Console.WriteLine(a);
                        break;
                    }
                    i++;
                }
                Console.ReadLine();

    while循环:

    其实是for循环的变形写法;

    for(int i=1;i<=5;i++)

    {

    循环体

    }

    =》

    int i=1;

    while(;i<=5;)

    {

    循环体;

    i++;

    }

     int a = 7;
                int i = 1;
                while(true)
                {
                    a *= 2;
                if(a>=884800000)
                {
                    Console.WriteLine(a);
                    Console.WriteLine(i);
                    break;
                }
                i++;
                }
                Console.ReadLine();
  • 相关阅读:
    js修改div标签中的内容
    echarts如何显示在页面上
    mybatis提取<where><if>共用代码
    部署LAMP-LAMP平台集成
    PHP安装指南
    部署LAMP-mysql 安装
    apache虚拟主机
    apache默认网站
    HDU 5375 Gray code 格雷码(水题)
    HDU 5371 Hotaru's problem (Manacher,回文串)
  • 原文地址:https://www.cnblogs.com/dongqiaozhi/p/5263407.html
Copyright © 2011-2022 走看看