C#_循环的中断continue,goto和return结束循环

循环的中断 continue(终止当前循环继续下一个循环)

使用continue,只会终止当次循环,继续运行下次循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _28
{
class Program
{
static void Main(string[] args)
{
//int a = 1;
//while (true)
//{
// a++;
// if (a==5)
// {
// continue;//跳过这次,不运行下面的代码
// }
// if (a==10)
// {
// break;//直接退出循环体
// }
// Console.WriteLine(a); //当index==5的时候,使用了continue关键字,那么continue后面的代码就不会去执行了,直接会进行循环的条件判断,根据判断结果判定是否执行下一次循环
//}

//接受用户输入的整数,如果用户输入的是大于0的偶数,就相加,如果用户输入的是大于0的奇数就不相加,如果用户输入的是0,就把和输出并退出程序
int sum = 0;
while (true)
{
int num = Convert.ToInt32(Console.ReadLine());
if (num==0)
{
break;
}
if (num%2==1)//如果和2求余结果是1,那么就是奇数,则跳转不继续下面的代码
{
continue;
}
sum += num;

}
Console.WriteLine(sum);
Console.ReadKey();
}
}
}

循环的中断 goto可以直接跳到某一个位置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _29
{
class Program
{
static void Main(string[] args)
{
//接受用户输入,如果输入的0,就使用goto退出循环
while (true)
{
int mun = Convert.ToInt32(Console.ReadLine());
if (mun==0)
{
goto mylabel;
}
}
mylabel: Console.WriteLine("跳出循环了");
Console.ReadKey();
}
}
}

循环的中断 return跳出循环(跳出函数)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _29
{
class Program
{
static void Main(string[] args)
{
//接受用户输入,如果输入的0,就使用return退出循环
while (true)
{
int num = Convert.ToInt32(Console.ReadLine());
if (num==0)
{
return;//用来终止方法的,表示方法运行结束,剩余的代码不执行了
}
}
Console.WriteLine("跳转循环了");
Console.ReadKey();
}
}
}