运算符'>'和'<'不能应用于'string'和'string'类型的操作数C#

Mik*_*x64 0 c# operator-keyword

在Visual Studio 2015中制作的C#程序,要求用户猜测1-10中的数字,该数字将告诉用户猜测是否正确,大于或小于必须猜测的值.

static void Main(string[] args)
    {
        string rightGuess = "7";

        Console.WriteLine("Guess the right number from 1-10: ");
        string userGuess;
        userGuess = Console.ReadLine();
        {
            if (userGuess == rightGuess)
                Console.WriteLine("You guessed right!");
            else if (userGuess > rightGuess)
                Console.WriteLine("Wrong guess. Your guess was greater than the right guess.");
            else (userGuess < rightGuess)
                Console.WriteLine("Wrong guess. Your guess was lesser than the right guess.");
        }
    }
Run Code Online (Sandbox Code Playgroud)

该程序在Visual Studio 2015中返回以下错误: 错误

已经在Google上研究了大约一个小时如何解决错误,但没有一个解决方案能够修复错误.

Kam*_*ski 5

您需要比较整数而不是字符串(以实现这种比较),将此行更改为:

int rightGuess = 7;

int userGuess = int.Parse(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)

它会起作用.当然,您可以添加int.TryParse并检查输入是否实际上是一个int

int userGuess;

if(int.TryParse(Console.ReadLine(), out userGuess))
{
    ... do your logic
}
else
{
    Console.WriteLine("Not a number");
}
Run Code Online (Sandbox Code Playgroud)