当前位置:编程学习 > C#/ASP.NET >>

流程控制语句(例子)

1,switch语句:判断用户输入的月份属于什么季节.
namespace switch语句  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            //判断用户输入的月份所在的季节  
            Console.WriteLine("请您输入一个月份!");   
            int MyMouth = int.Parse(Console.ReadLine());            //变量MyMouth用于获取用户输入的数据  
  
            string MySeason;  
            switch (MyMouth)  
            {   
                case 12:  
                case 1:  
                case 2:  
                      MySeason ="此月份是冬季!学敏记得保暖哦!";  
                       break;                                        //跳出switch语句  
                case 3:  
                case 4:  
                case 5:  
                    MySeason ="此月份是春季!学敏记得戴眼镜,避大风哦!";  
                    break;  
                case 6:  
                case 7:  
                case 8:  
                    MySeason ="此月份是夏季!学敏记得吃雪糕,穿热裤哦!";  
                    break;  
                case  9:  
                case 10:  
                case 11:  
                     MySeason ="此月份是秋季!学敏这是个丰收的季节,给家里常打电话问候哦!";  
                     break;  
                default :  
                     MySeason = "月份输入错误!学敏温馨提示:只存在1~12月哦,亲!";  
                    break;  
            }  
  
            Console .WriteLine (MySeason );  
            Console .ReadLine ();  
  
        }  
    }  
}  
 
 
运行结果:
 
2,while语句:声明两个int型变量 为s、num,初始值分别为0和100. 通过while语句循环输出。当s>50时,使用break语句终止循环;当s为偶数时,使用continue开始下一个循环。
namespace while语句  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            //当s>50时,使用break语句终止循环;当s为偶数时,使用continue开始下一个循环  
             int s = 0;  
            int num = 100;  
  
            while (s < num)  
            {  
                s++;  
  
                if (s > 50)  
                { break; }  
  
                if (s % 2 == 0)  
                { continue; }  
  
                Console.Write(s+" ");  
    
            }  
            Console.WriteLine("\n 学敏,以上就是0到50的所有奇数的输出!请注意查收!");  
            Console.ReadLine();  
        }  
    }  
}  
 
运行结果:
 
4,for语句:声明一个int类型的数组,然后向数组中添加5个值,最后使用for循环语句遍历数组,并将数组中的值输出.
namespace for语句  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            string[]xuemin;  
            xuemin=new string [5];                       //声明一个具有5个元素的string型数组  
  
            xuemin[0] = "大家好!";                      //向数组中添加元素  
            xuemin[1] = "我叫韩学敏";  
            xuemin[2] = "我喜欢学习计算机!";  
            xuemin[3] = "谢谢我的恩师—米新江!!!";  
            xuemin[4] = "我会好好努力的,投入百分之百的热情!";  
  
            for (int i = 0; i < xuemin.Length; i++)                      //利用for语句  输出数组中的每个元素  
            {  
                Console .WriteLine ("xuemin [{0}]的值为:{1}",i ,xuemin [i ]);       
  
            }  
            Console .ReadLine ();  
   
补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,