代碼跳過錯誤 if 陳述句并直接轉到 else if
我需要經過幾圈,如果它小于 2 圈,那么它會出現錯誤并再次回來要求輸入一個新值。反之亦然大于 20。我是一名新程式員,發現 C# Windows 表單很難理解
int.TryParse(txtNumberOfLaps.Text, out laps);
while (laps < 2 && laps > 20)
{
if (laps < 2)
{
MessageBox.Show("Laps can't be less than 2", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (laps > 20)
{
MessageBox.Show("Laps can't be more than 20", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (laps > 2 && laps < 20)
{
break;
}
}
uj5u.com熱心網友回復:
從我所看到的,我認為您的代碼沒有進入 while 回圈。你在問laps < 2 AND laps > 20
,而我認為你想要的是什么laps < 2 OR laps > 20
。您的回圈沒有意義,因為您的數字不能同時大于 20 且小于 2
uj5u.com熱心網友回復:
永遠不會進入 while 回圈,因為一個數字不能同時小于 2 和大于 20。laps < 2 && laps > 20
應該是laps < 2 || laps > 20
更正這一點,如果數字低于 2 或高于 20,則進入 while 回圈,但最后一個 else-if 陳述句永遠不會為真。
如果數字在范圍內,則永遠不會進入 while 回圈,因此不會命中任何 if 陳述句。
這是一個關于如何解決您描述的問題的示例。
while (true)
{
Console.WriteLine("Please enter a number between 2 and 20:");
var input = Console.ReadLine();
if (!int.TryParse(input, out var number))
{
// the input could not be parsed
Console.WriteLine("Please enter a proper numeric value.");
}
else if (number < 2)
{
Console.WriteLine("The number can't be less than 2");
}
else if (number > 20)
{
Console.WriteLine("The number can't be more than 20");
}
else
{
// if all if-statements above is false, the number must be between 2 and 20
Console.WriteLine($"You entered {number}. Good job!");
break;
}
}
這看起來像是您第一次學習編程時要解決的早期問題之一。這有點像一個技巧問題,其中有多個缺陷供您發現。
uj5u.com熱心網友回復:
它跳到哪個else if
?您的回圈包含兩個。我想由于回圈的哨兵值無法滿足,程式甚至在開始回圈之前就退出了。對于任何給定的 integer n
,20>n<2
都不存在。這實際上是不可能的。您可以通過檢查使while
回圈的每個條件為真的數字來看到這一點。例如
n < 2
最容易通過提供一個來滿足1
。
n = 1
然而,使n > 20
虛假。
另一方面,
n > 20
最容易通過提供21
作為引數來實作。
n = 21
使您的第一個條件為n<2
假,因此您的回圈永遠不會開始
因此,在任何情況下n
,您的while
回圈都不會收到初始True
值來開始。
既然已經解決了,讓我們為您提供解決方案!:)
你正在尋找的是這樣的:
int.TryParse(txtNumberOfLaps.Text, out laps);
while(true)
{
if (laps < 2 || laps > 20)
{
MessageBox.Show("Laps must be in range 2-20", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
else
{
// do other things
break;
}
}
uj5u.com熱心網友回復:
問題在這里:
while (laps < 2 && laps > 20)
它不能同時低于 2 和高于 20,因此回圈永遠不會執行。使用||
代替,&&
它會作業。
同樣,一旦進入回圈,最后的else if
陳述句是多余的,可以洗掉。如果該條件為真,它無論如何都會從回圈中中斷。
此代碼將起作用:
int.TryParse(txtNumberOfLaps.Text, out laps);
while (laps < 2 || laps > 20)
{
if (laps < 2)
{
MessageBox.Show("Laps can't be less than 2", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show("Laps can't be more than 20", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/450526.html
標籤:C# if 语句 while循环 条件语句 布尔表达式
下一篇:我將如何寫這個if陳述句