如何结束循环
本文关键字:循环 结束 何结束 | 更新日期: 2023-09-27 18:28:25
开始学习循环。这些事情似乎永远都在继续,因为我没有告诉它停止。问题是我不知道该怎么叫它停下来。我假设一个语句,如!=但我真的不知道。
有人想解释一下循环是如何停止的吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication326
{
class Program
{
static void Main(string[] args)
{
bool triLoop = true;
while (triLoop)
{
Console.WriteLine("Please enter the first integer...");
int firstInt = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the second integer...");
int secondInt = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the third integer...");
int thirdInt = int.Parse(Console.ReadLine());
if ((firstInt + secondInt > thirdInt) && (secondInt + thirdInt > firstInt) && (firstInt + thirdInt > secondInt))
{
Console.WriteLine("The numbers {0}, {1}, and {2} CAN represent sides of the same triangle.", firstInt, secondInt, thirdInt);
}
else
{
Console.WriteLine("The numbers {0}, {1}, and {2} CANNOT represent the sides of the same triangle.", firstInt, secondInt, thirdInt);
}
}
}
}
}
break
语句将"中断"循环。
或者,您可以将布尔值(triLoop
)设置为false
。
任何人都想解释循环如何停止
只要循环中的条件为true,While循环就会运行。为了打破它,您需要将while循环中的表达式设置为false。
当您将triLoop
设置为false时,它将停止。您应该阅读文档。
while(triLoop)
{
if(somecondition)
triLoop = false; //loop will not run after this
}
这是一个基本的例子。这个循环将运行到5点。
int n = 1;
while (n < 6)
{
Console.WriteLine("Current value of n is {0}", n);
n++;
}
将triLoop
设置为false
。或者使用break;
。
其他答案已经解释了条件是如何工作的,但如果你想询问用户是否想继续,你可以将其添加到循环的末尾:
Console.WriteLine("Would you like to continue? (Y/N)");
if(Console.ReadLine() == "Y")
triLoop = false;
然后,如果用户键入"Y",条件将计算为false,循环将结束。
有多个答案。
break; //exits the loop and continues with the code
return; //stops the loop and doesn't proceed with the rest of the code
在您的情况下,您还可以将triloop设置为false。
在循环中使用此选项来停止循环
break;
当您使用while
循环时
while (triLoop)
{
}
该循环在triLoop
变量为true
时运行
您需要在while
循环中的某个位置将其设置为false
像
while (triLoop)
{
//your code
// on some condition
triLoop = false;
}
或
while (triLoop)
{
//your code
// on some condition
break;
}
试试这个:
while (triLoop)
{
Console.WriteLine("Please enter the first integer...");
int firstInt = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the second integer...");
int secondInt = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the third integer...");
int thirdInt = int.Parse(Console.ReadLine());
if ((firstInt + secondInt > thirdInt) && (secondInt + thirdInt > firstInt) && (firstInt + thirdInt > secondInt))
{
Console.WriteLine("The numbers {0}, {1}, and {2} CAN represent sides of the same triangle.", firstInt, secondInt, thirdInt);
}
else
{
Console.WriteLine("The numbers {0}, {1}, and {2} CANNOT represent the sides of the same triangle.", firstInt, secondInt, thirdInt);
}
Console.WriteLine("press 0 if you want to continue...");
int flag = int.Parse(Console.ReadLine());
if(flag!=0) break;
}