原文: https://www.programiz.com/c-programming/c-break-continue-statement
我们在之前的教程中了解了循环。 在本教程中,我们将在示例的帮助下学习使用break和continue语句。
C break
break语句在遇到循环时将立即结束循环。 其语法为:
break;
break语句几乎总是与循环内的if...else语句一起使用。
break语句如何工作?

示例 1:break语句
// Program to calculate the sum of a maximum of 10 numbers// If a negative number is entered, the loop terminates# include <stdio.h>int main(){int i;double number, sum = 0.0;for(i=1; i <= 10; ++i){printf("Enter a n%d: ",i);scanf("%lf",&number);// If the user enters a negative number, the loop endsif(number < 0.0){break;}sum += number; // sum = sum + number;}printf("Sum = %.2lf",sum);return 0;}
输出
Enter a n1: 2.4Enter a n2: 4.5Enter a n3: 3.4Enter a n4: -3Sum = 10.30
该程序计算最多 10 个数字的总和。 为什么最多 10 个数字? 这是因为如果用户输入一个负数,则将执行break语句。 这将结束for循环,并显示sum。
在 C 中,break也与switch语句一起使用。 这将在下一个教程中讨论。
C continue
continue语句跳过循环的当前迭代,并继续下一个迭代。 其语法为:
continue;
continue语句几乎总是与if...else语句一起使用。
continue语句如何工作?

示例 2:continue语句
// Program to calculate the sum of a maximum of 10 numbers// Negative numbers are skipped from the calculation# include <stdio.h>int main(){int i;double number, sum = 0.0;for(i=1; i <= 10; ++i){printf("Enter a n%d: ",i);scanf("%lf",&number);if(number < 0.0){continue;}sum += number; // sum = sum + number;}printf("Sum = %.2lf",sum);return 0;}
输出
Enter a n1: 1.1Enter a n2: 2.2Enter a n3: 5.5Enter a n4: 4.4Enter a n5: -3.4Enter a n6: -45.5Enter a n7: 34.5Enter a n8: -4.2Enter a n9: -1000Enter a n10: 12Sum = 59.70
在此程序中,当用户输入正数时,将使用sum += number;语句计算总和。
当用户输入一个负数时,将执行continue语句,并从计算中跳过该负数。
