while循环中的break和continue

it2024-03-11  63

 

break和continue的区别

break:永久终止循环,break后面的部分不再执行,while循环也结束。 continue:结束本次循环,本次循环continue后的部分不再执行,开始下一次循环判断。

#include<stdlib.h> #include<stdio.h> int main() { int i = 1; while (i <= 10) { if (i == 5) break; printf("%d ", i); i++; } system("pause"); return 0; }

输出结果为1 2 3 4

#include<stdlib.h> #include<stdio.h> int main() { int i = 1; while (i <= 10) { if (i == 5) continue; printf("%d ", i); i++; } system("pause"); return 0; }

死循环,输出1 2 3 4 在i=5时陷入死循环。但要是采用for循环的话这里不会陷入死循环。

#include<stdlib.h> #include<stdio.h> int main() { int i = 1; for (i = 1; i <= 10;i++) { if (i == 5) continue; printf("%d ", i); } system("pause"); return 0; }

输出结果为 1 2 3 4 6 7 8 9 10

最新回复(0)