简体   繁体   English

如何正确编写(userInput> =“ 50”)?

[英]How can I write (userInput >= “50”) properly?

I mean to say "If the number typed by the user is greater than 50 then..." How can I write this properly? 我的意思是说:“如果用户键入的数字大于50,则...”如何正确书写? Because this error shows up in Visual Studio: 由于此错误显示在Visual Studio中:

Operator '>=' cannot be applied to operands of type 'string' and 'string' 运算符'> ='不能应用于类型为'string'和'string'的操作数

Console.Write("Enter a number: ");
        string userInput = Console.ReadLine();
        string message = (userInput >= "50") ? "Your number is greater than 50" : "You number is less than 50";

        Console.WriteLine(message);
        Console.ReadLine();

Strings are not numbers, so parse it: 字符串不是数字,因此请解析它:

int userInputNum = 0;
string userInput = Console.ReadLine();

if (int.TryParse(userInput, out userInputNum))
{
    string message = (userInputNum > 50) ? "Your number is greater than 50" : "You number is less than 50";
    Console.WriteLine(message);
}
else
{
    //Junk user input
}

Note that you can use int.Parse instead, but it will throw if the user inputs a non-number. 请注意,您可以改用int.Parse ,但是如果用户输入非数字,它将抛出该int.Parse The out keyword in the second argument forces the called function to populate the argument before returning (used because the signature of TryParse calls for it). 第二个参数中的out关键字会强制被调用的函数在返回之前填充该参数(之所以使用,是因为TryParse的签名要求它)。 Also, your logic was greater than or equal to 50. The code above is strictly greater than. 另外,您的逻辑大于或等于 50。以上代码严格大于。

Your original code doesn't work because you are comparing the user input to a string (hence the "cannot be applied to operands of type 'string' and 'string' " ) because you have compared it to "50" . 您的原始代码无效,因为您正在将用户输入与字符串进行比较(因此, “您无法将其应用于'string'和'string' “类型的操作数 ),因为您已将其与"50" A string cannot be "greater than" or "less than" another string, only "equal to" ( == ) or "not equal to" ( != ). 一个字符串不能“大于”或“小于”另一个字符串,只能是“等于”( == )或“不等于”( != )。

More specifically, the > operator is not defined on string and so cannot be used to compare two of them. 更具体地说, >运算符未在string定义,因此不能用于比较它们中的两个。

change this 改变这个

 string userInput = Console.ReadLine();

to

 var userInput = Convert.ToInt32(Console.ReadLine());

and (userInput >= "50") to 和(userInput> =“ 50”)到

(userInput >= 50)

just remove qoutations 只需删除qoutations

You've stored the value in a string variable. 您已将值存储在字符串变量中。 Thus, you should convert it to int so you are able to compare. 因此,您应该将其转换为int,以便能够进行比较。

Console.Write("Enter a number: ");
    string userInput = Console.ReadLine();
    string message = (Convert.ToInt32(userInput) >= 50) ? "Your number is greater than 50" : "You number is less than 50";

    Console.WriteLine(message);
    Console.ReadLine();

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

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