如何在 C# 中使用 break 和 continue 语句控制 for 循环?


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;
}

同理,continue 语句在 for 循环中也会起作用,但它不会显示负数。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;
}

更新于: 2020-06-20

156 次浏览

开启您的 职业

完成课程认证

开始
广告
© . All rights reserved.