138-循环的中断continue,goto和return结束循环

continue终止当次循环,继续运行下次循环

return终止方法,表示方法运行结束,剩余代码不执行

练习:接受用户输入的整数,如果用户输入的是大于0的偶数,就相加,如果用户输入的是大于0的奇数就不相加,如果用户输入的是0,就把和输出并退出程序

            int sum = 0;
            while (true)
            {
                //string str = Console.ReadLine();
                //int num = Convert.ToInt32(str);
                int num = Convert.ToInt32(Console.ReadLine());
                if (num == 0)
                {
                    break;
                }
                if (num%2 == 1)
                {
                    continue;
                }
                sum += num;
            }
            Console.WriteLine(sum);
            Console.ReadKey();

接受用户输入,如果输入的0,就使用goto退出循环

while (true)
{
    int num = Convert.ToInt32(Console.ReadLine());
    if (num == 0)
    {
        goto myLabel;
    }
}
myLabel:
Console.WriteLine("跳出循环了");

接受用户输入 ,如果输入0,就使用return 跳出循环

            while (true)
            {
                int num = Convert.ToInt32(Console.ReadLine());
                if (num == 0)
                {
                    return;//用来终止方法的,表示方法运行结束,剩余的代码不执行了
                }
            }
            Console.WriteLine("跳出循环了");
            Console.ReadKey();

  

  

posted @ 2018-11-16 16:05  阿晖2222  阅读(247)  评论(0编辑  收藏  举报