万金流
初次使用博客园,目前感觉还不错。 不知不觉用了4年零4个月了,越来越喜欢博客园。

P178循环结构

大侠练功

P187while循环和P189do....while循环格式

注意分号。

小结:1、写出代码,找到循环部分,用循环代码完成。2、特别注意检查第一次进循环和最后出循环的时候,是否符合编程意图。

例:输个数,打个数,遇0停止。

小技巧:可变部分,找到变化规律,用变量实现。

例:打自然数序列1-100

练习:

1、输入一个数,打印它的2倍,输入0为止。

对于while循环和do-while循环,最大的区别在于先判断,还是先执行一次循环体再判断。

仔细体会下面两段程序的不同(第一次输入0时):

int a = 0;
            //while (a != 0)
            //{
            //    a = int.Parse(Console.ReadLine());
            //    Console.WriteLine(2*a);
            //}
            do
            {
                a = int.Parse(Console.ReadLine());
                Console.WriteLine(2 * a);
            }
            while (a != 0);

2、小练习:到兔子家做客,点的菜不是胡萝卜,兔子就不停问。

string s;
            do
            {
                Console.WriteLine("eat what?");
                s = Console.ReadLine();
            }
            while (s != "胡萝卜");
            Console.WriteLine("good");

FOR循环  P179

适用于已知起止数

3、1+2+3+...+100

4、打印所有水仙花数

int b, s, g;
            for (int i = 100; i < 1000; i++)
            {
                b = i/100;
                s = i % 100 / 10;
                g = i % 10;
                if(b*b*b+s*s*s+g*g*g==i)
                {
                    Console.WriteLine(i);
                }
            }

 

(P185  BREAK和CONTINUE)

break:跳出当前循环

continue:结束本次循环

例:输入a,1+2+...+a,最多加到10

int a,s=0;
            a = int.Parse(Console.ReadLine());
            for (int i = 1; i <= a; i++)
            {
                if (i > 10)
                {
                    break;
                }
                s += i;
            }
            Console.WriteLine("s=" + s);

计算1....a中所有偶数的和(排除奇数)

int a,s=0;
            a = int.Parse(Console.ReadLine());
            for (int i = 1; i < a; i++)
            {
                if (i %2==1)
                {
                    continue;
                }
                s += i;
            }
            Console.WriteLine("s=" + s);

P194练习

posted on 2020-10-26 11:35  万金流  阅读(467)  评论(0编辑  收藏  举报