Break 语句终止循环。要在 for 循环中使用它,您可以每次都获取用户的输入,并在用户输入负数时显示输出。然后显示输出并使用break语句退出 -
for(i=1; i <= 10; ++i) {
myVal = Console.Read();
val = Convert.ToInt32(myVal);
// loop terminates if the number is negative
if(val < 0) {
break;
}
sum += val;
}
同样,for 循环中的 continue 语句也可以工作,但不会显示负数。 continue 语句使循环跳过其主体的其余部分,并在重复之前立即重新测试其条件 -
for(i=1; i <= 10; ++i) {
myVal = Console.Read();
val = Convert.ToInt32(myVal);
// loop terminates if the number is negative and goes to next iteration
if(val < 0) {
continue;
}
sum += val;
}