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

来源:这里教程网 时间:2026-02-21 16:19:53 作者:

如何在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;
}

同样,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;
}

相关推荐