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

查看:951
本文介绍了运算符'=='不能应用于'int'和'string类型的操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,我想到一个数字,而计算机猜测它。我正在尝试测试它,但我一直都会遇到错误。错误是主题标题。我使用Int.Parse转换我的字符串,但我不知道为什么我收到错误。我知道它说'=='不能和整数一起使用,但是我在网上看到的所有内容以及我班上的幻灯片都使用它,所以我被卡住了。代码是不完整的,我不想让它运行,我只是想解决问题。非常感谢任何帮助,谢谢:D

I'm in the middle of writing a program where I think of a number, and the computer guesses it. I'm trying to test it as I go along, but I keep getting an error I should'nt be. The error is the topic title. I used Int.Parse to convert my strings, but I don't know why I'm getting the error. I know it says '==' can't be used with integers, but everything I've seen online plus the slides from my class all use it, so I'm stuck. The code is incomplete and I'm not trying to get it to run yet, I just want to fix the problem. I appreciate any help a lot, thanks :D

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Enter any number after 5 to start: ");
        int answer = int.Parse(Console.ReadLine());
        {
            Console.WriteLine("is it 3?");
            if (answer == "higher")


推荐答案

你要求一个数字,但是你试图将它与非数字数据进行比较。忘记语言语义,你如何期望将数字文本进行比较?如果像3这样的数字是否等于更高是什么意思?

You ask for a number, but you are trying to compare it to non-numeric data. Forget language semantics, how do you expect to compare a number to text? What does it mean to ask if a number like 3 is equal to "higher"?

答案是它是荒谬的;这是语言不允许的原因之一。

The answer is that it is nonsensical; this is one reason why the language does not allow it.

int a = 1;
string b = "hello";

if (a == 1)       { /* This works; comparing an int to an int */ }
if (a == "hello") { /* Comparing an int to a string!? This does not work. */ }
if (b == 1)       { /* Also does not work -- comparing a string to an int. */ }
if (b == "hello") { /* Works -- comparing a string to a string. */ }

您可以通过将数字转换为字符串来强制进行比较:

You can force the comparison to compile by converting your number to a string:

if (answer.ToString() == "higher")

但是这个条件永远不会被满足因为没有 int 将转换为文本hello的值。 if 块内的任何代码都将保证永远不会执行。你也可以写 if(false)

But this condition will never be met because there is no int value that would convert to the text "hello". Any code inside of the if block would be guaranteed never to execute. You might as well write if (false).

这篇关于运算符'=='不能应用于'int'和'string类型的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆