[英]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.