三种循环语句:
for
while
foreach

循环四要素:
初始条件,循环条件,循环体,状态改变

for(初始条件;循环条件;状态改变)
{
循环体;
}

基本结构:
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("hello world!" + i);
}

最容易晕的地方:
1、到低循环几遍
2、循环条件表达式的写法

死循环:
for(;;)
{

}

while(循环条件true)
{

}

跳转语句:
break; 只要程序在循环中看到这句话,就会立刻终止循环并且跳出循环;
continue; 只要程序在循环中看到这句话,就会立刻终止此次循环;
return;//用在函数里

 

练习1

随机抽取一个手机号

           //随机抽取一个手机号

            Console.Write("请输入随机抽奖的秒数");
            int a = Convert.ToInt32(Console.ReadLine());
            int aa = 0;
            Console.Write("按下空格键开始");
            ConsoleKeyInfo b = Console.ReadKey();
            if (b.Key.ToString() == "Spacebar")
            {  
                Random r = new Random();
                //持续滚动手机号
                for (; ; )
                {
                    Thread.Sleep(100);
                    string tel = "1";
                    tel += r.Next(10000,99999);
                    tel += r.Next(10000, 99999);
                    Console.Clear();
                    Console.WriteLine(tel);
                    Console.WriteLine("距离结束还有"+(a-aa/1000)+"");
                    aa += 100;
                    if (aa == a * 1000)
                    {
                        Console.Clear();
                        Console.WriteLine("恭喜中奖手机号码是13478965676的观众");
                        break;
                    }
                }
            }

            Console.ReadLine();

运算结果

练习            //让用户循环操作,用户输入一个正整数(0-20),如果小于0或大于20都提示输入错误,

//如果输入的是0-20之间的数,那么就打印从0到这个数的累加求和,
            //一共需要用户输入3遍,输入错误不计入这3遍操作当中
            int count=0;
            for (; ; )
            {
                //用户输入一个正整数
                Console.Write("用户输入一个正整数(0-20):");
                int a = Convert.ToInt32(Console.ReadLine());
                int c = 0;//最后的总和
                //判断是否输入正确
                if (a >= 0 && a <= 20)
                {
                    for (int b = 0; b <= a; b++)
                    {
                        c += b;
                    }
                    Console.WriteLine(c);
count ++;
Console.WriteLine("输入"+count+"次");
if(count==3)
{
Console.WriteLine("输入结束");
break;
}
}
else { Console.WriteLine("输入错误"); } } Console.ReadLine();

运算结果

posted on 2016-05-22 20:27  斐雪  阅读(167)  评论(0编辑  收藏  举报