如果条件未达到,在尝试循环时执行while问题
本文关键字:循环 执行 while 问题 条件 未达到 如果 | 更新日期: 2023-09-27 18:17:34
我试图通过输入10-50之间的整数来让我的程序工作,如果他们没有在可接受的范围内输入,循环将通过再次输入而返回。但我似乎不明白为什么我的程序不起作用。我知道背后的逻辑,但我认为代码是问题所在。这是我的代码
Console.WriteLine("Enter a digit between 10 and 50 ");
xx = Console.ReadLine();
x = int.Parse(xx);
do
{
if (x > 10 && x < 50)
Console.WriteLine("Pleae input again: ");
}
while (x <= 10 && x >= 50);
Console.WriteLine("The number is in between!");
Console.Read();
if
条件错误,while
条件错误!
试试这个:
Console.WriteLine("Enter a digit between 10 and 50 ");
do
{
xx = Console.ReadLine();
x = int.Parse(xx);
if (10 <= x && x <= 50)
break;
Console.WriteLine("Pleae input again: ");
}
while (true);
这个怎么样:
string xx;
int x;
Console.WriteLine("Enter a digit between 10 and 50 ");
bool cont = true;
do
{
xx = Console.ReadLine();
if (int.TryParse(xx, out x) && 10 <= x && x <= 50)
cont = false;
else
Console.WriteLine("Pleae input again: ");
}
while (cont);
看到while(true)
使我起鸡皮疙瘩。并且,对于用户输入,您应该始终使用int.TryParse
而不是int.Parse
。
检查IF和WHILE条件。试试这个:
Console.WriteLine("Enter a digit between 10 and 50 ");
do
{
xx = Console.ReadLine();
x = int.Parse(xx);
if (x <= 10 || x >= 50)
Console.WriteLine("Pleae input again: ");
}
while (x <= 10 || x >= 50);
Console.WriteLine("The number is in between!");
Console.Read();
你需要每次都请求输入,否则你将无法跳出循环。
do
{
xx = Console.ReadLine();
x = int.Parse(xx);
if (x > 10 && x < 50)
Console.WriteLine("Pleae input again: ");
}
while (x <= 10 && x >= 50);
Console.WriteLine("The number is in between!");
Console.Read();