[英]while loop conditions with more than 1 condition/condition type C#
試圖讓我的 while 循環有 1 個以上的條件,基本上用戶輸入一個數字高度,代碼繼續等等。高度數據將傳遞給代碼以供以后計算。
目前我已將其設置為當用戶未輸入數字(例如字母“H”)時,它會進入 while 循環以獲取錯誤消息。 但是,我還希望輸入的高度不能超過 3 的條件,如果說用戶輸入 5,它也會進入錯誤消息的循環。 目前當進入循環用戶可以重試並輸入一個數字(可以輸入字母會繼續返回)。 在我的 while 條件中,我嘗試添加 && (heightM >3) - (while (double.TryParse(userInput, out double heightM)&& (heightM <3) == false) - 但似乎沒有做我想要的。在在這種情況下,它會忽略 tryparse,如果用戶輸入 4,它會正確循環,但如果是一個字母,應用程序會崩潰。
我很新 - 仍在學習,抱歉,如果這是一個簡單的問題:/
double height;
string userInput = Console.ReadLine().ToLower();
while (double.TryParse(userInput, out double heightM) && (heightM<3) == false)
{
Console.Clear();
Console.WriteLine("Incorrect value or input");
Console.WriteLine("");
Console.WriteLine("Enter Height in Meters only up to Maxmium of 3 meters");
userInput = Console.ReadLine().ToLower();
}
height = double.Parse(userInput);
使用while(true)
循環,我們可以檢查條件並break
循環,否則循環將一直持續到輸入正確的值。
double height;
double maxHeight = 3;
while (true)
{
var userInput = Console.ReadLine();
if (double.TryParse(userInput, out var heightM) && heightM <= maxHeight)
{
height = heightM;
break;
}
Console.Clear();
Console.WriteLine($"Please enter Height in Meters only up to maximum of {maxHeight} meters");
}
Console.WriteLine(height);
解析不是數字的字符串將導致 out 變量設置為 0,因此您的邏輯存在缺陷。 相反,您應該將其更改為
double heightM;
string userInput = Console.ReadLine().ToLower();
while (!double.TryParse(userInput, out heightM) || (heightM > 3))
{
....
}
第一個變化是使用單個 hejghtM 變量,第二個變化是我們如何測試 TryParse 的結果,如果解析失敗我們可以立即輸入重試代碼。 所以第三個變化是使用 || 而不是 && ,這導致了第四個變化,我們測試大於 3 的值以進入重試循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.