码迷,mamicode.com
首页 > 其他好文 > 详细

7.24 学习笔记 for循环的嵌套,for循环的穷举迭代

时间:2016-07-24 17:44:46      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

for循环的嵌套
            输入一个正整数,求阶乘的和 

嵌套
            Console.Write("请输入一个正整数:");
            int a = int.Parse(Console.ReadLine());
            int sum = 0;
            for (int i = 1; i <= a; i++)
            {
              int jie = 1;
              for (int j = 1; j <= i; j++)
               {
            jie *= j;
                }
               sum += jie;
            }
            Console.WriteLine("结果是:" + sum);
            Console.ReadLine();
                  99口诀表
            for (int i = 1; i <= 9; i++)
            {
                for (int j = 1; j <= i; j++)
                {
                    Console.Write("{0}*{1}={2}\t",j,i,(j*i));
               }
                Console.Write("\n");
            }

           Console.ReadLine();

            直角在右下角的三角形
            for (int i = 1; i <= 5; i++)
            {
               for (int j = 1; j <= 5 - i; j++)
                {
                    Console.Write("  ");
               }
                for (int j = 1; j <= i; j++)
                {
                    Console.Write("□");
               }
               Console.WriteLine();
            }

            Console.ReadLine();

      

循环可以解决的问题类型
            穷举,把所有可能的情况都走一遍,使用if条件筛选出来满足条件的情况。

            单位给发了一张150元购物卡,
            拿着到超市买三类洗化用品。
            洗发水15元,香皂2元,牙刷5元。
           求刚好花完150元,有多少种买法,
            每种买法都是各买几样?
            洗发水 x  10
            牙刷    y  30
            香皂    z  75
            int ci = 0;
            int biao = 0;
            for (int x = 0; x <= 10; x++)
            {
                for (int y = 0; y <= 30; y++)
                {
                    for (int z = 0; z <= 75; z++)
                    {
                        ci++;
                        if (15 * x + y * 5 + z * 2 == 150)
                        {
                            biao++;
                            Console.WriteLine("第{0}种买法:洗发水{1}瓶,牙刷{2}支,香皂{3}块。", biao, x, y, z);
                        }
                    }
                }
            }
            Console.WriteLine("总共有{0}种买法。", biao);
            Console.WriteLine(ci);
            Console.ReadLine();

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

纸张可以无限次对折,纸张厚度为0.07毫米。
            问多少次对折至少可以超过8848?
            double height = 0.07;//8848m=8848000
            int ci = 0;
            while(height<=8848000)
            {
              ci++;
              height *= 2;//height=height*2;
            }
            Console.WriteLine(ci);
            Console.ReadLine();

 

7.24 学习笔记 for循环的嵌套,for循环的穷举迭代

标签:

原文地址:http://www.cnblogs.com/fuze/p/5700910.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!