为什么我的 TryParse 代码在 C# 中不起作用?

Why is my TryParse code not working in C#?

我的 while 循环有问题,我不知道是什么问题:

double d = 0;

while (!Double.TryParse(Console.ReadLine(), d <= 20 && d >= 1, out d))
{
    Console.WriteLine("The number is incorrect, please write in again");
}

因为你误解了tryparse,d是在try parse之后设置的,那你可以对比一下,你把边界检查放在了try parse的参数中:

while (!Double.TryParse(Console.ReadLine(), out var d) || d <= 20 && d>=1)
{    //you first check if you can parse it, and after parse is true, check if value is in your boundaries
     Console.WriteLine("The number is incorrect, please write in again");
}
double d = 0;

while (!Double.TryParse(Console.ReadLine(), out d) && d <= 20 && d >= 1)
{
    Console.WriteLine("The number is incorrect, please write in again");
}

像这样。您不小心将 d <= 20 && d >= 1 作为参数传递给 TryParse,而不是将其用作 while 循环的附加条件。