
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;
}以上就是如何在C#中使用break和continue语句控制for循环?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号