【2017-12-07】c#基础-跳转语句、异常语句、穷举法

1.跳转语句

  break - 跳出循环

            int count = 0;
            for (int i = 1; i <= 10; i++)
            {
                if (i == 5)
                    break;
                count ++;
            }
            Console.Write(count);//输出4

  continue - 停止当前次循环,继续下一次循环

1             int count = 0;
2             for (int i = 1; i <= 10; i++)
3             {
4                 if (i == 5)
5                     continue;
6                 count ++;
7             }
8             Console.Write(count);//输出9

2.异常语句 

  try...catch...(最后还可接finally,意思是不管是否有错都走这,一般不用写)

 1             Console.Write("请输入一个数字:");
 2             try
 3             {
 4                 int a = Convert.ToInt32(Console.ReadLine());
 5                 Console.WriteLine("你输入的数字是:" + a);
 6             }
 7             catch
 8             {
 9                 Console.WriteLine("你输入的不是数字!");
10             }
11             finally
12             {
13                 Console.WriteLine("加不加我都一样");
14             }
15             Console.WriteLine("上一句和我没区别");

3.穷举法

  循环嵌套+分支语句(个人理解)

  代表题目:百鸡百钱
  有100文钱,小鸡0.5文钱 ,母鸡1文钱,公鸡2文钱。买一百只鸡钱刚好花完,问有多少种可能。

 1             int count = 0;
 2             for (int x = 0; x <= 200; x++)
 3             {
 4                 for (int m=0;m<=100;m++)
 5                 {
 6                     for (int g = 0; g <= 50; g++)
 7                     {
 8                         if (x * 0.5 + m * 1 + g * 2 == 100 && x + m + g == 100)
 9                         {
10                             count++;
11                             Console.WriteLine(count + ".买" + x + "只小鸡," + m + "只母鸡," + g + "只公鸡。");
12                         }
13                     }
14                 }
15             }
16             Console.WriteLine("共有"+count+"种可能!");
17             Console.ReadLine();

 


 

练习:

让用户输入一个数字
判断用户输入的是不是数字,
如果是数字,则绕了他,完事
如果不是数字,那么就告诉他一声,然后让他重新再输入,直到输入的是数字为止.

 1             Console.Write("请输入一个数字:");
 2             while (true)
 3             {               
 4                 string a = Console.ReadLine();
 5                 try
 6                 {
 7                     int b = Convert.ToInt32(a);
 8                     Console.WriteLine("输入正确,你输入的是:" + b);
 9                     break;
10                 }
11                 catch
12                 {
13                     Console.Write("输入错误,请重新输入:");
14                 }
15             }

 

posted @ 2017-12-07 16:34  Int64  阅读(98)  评论(0编辑  收藏  举报