简体   繁体   English

捕获1-100之间的整数

[英]Capture an integer between 1-100

I'm trying to capture a number between 1 and 100 in C#, I would like to loop the user until they enter the correct result. 我试图在C#中捕获1到100之间的数字,我想循环用户,直到他们输入正确的结果。 I have the following but it isn't evaluating like I expect, where is the gap in my knowledge? 我有以下内容,但它没有像我期望的那样进行评估,我的知识差距在哪里?

var input=0;

Console.Write("Enter a number between 1 and 100: ");

while (!int.TryParse(Console.ReadLine(), out input) && input>0 && input <=100)
{
    Console.Write("The value must be a number greater than 0, but less than 100 please try again: ");
}

It seems you are missing a pair of parenthesis and !int.TryParse(Console.ReadLine(), out input) is evaluated and false if the user inputs anything. 似乎您缺少一对括号,并且对!int.TryParse(Console.ReadLine(), out input)进行了评估,如果用户输入了任何内容,则为false。

Try with: 尝试:

var input=0;

Console.Write("Enter a number between 1 and 100: ");

while (!(int.TryParse(Console.ReadLine(), out input) && input>0 && input <=100))
{
    Console.Write("The value must be a number greater than 0, but less than 100 please try again: ");
}
 static void Main(string[] args)
    {
        var input = 0;
        Console.Write("Enter a number between 1 and 100: ");
        while (true)
        {
          if (int.TryParse(Console.ReadLine(), out input) && (input < 0 || input > 100))
            {
                Console.Write("The value must be a number greater than 0, but less than 100 please try again: ");
            }
            else
            {
                Console.WriteLine("Thank you for the correct input");
                break;
            }
        }
        Console.ReadKey();        

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM