运算符’==’不能应用于’int’和’string类型的操作数
我正在写一个程序,我想到一个数字,计算机猜测它。 我正在尝试测试它,但我一直都会遇到错误。 错误是主题标题。 我使用Int.Parse转换我的字符串,但我不知道为什么我收到错误。 我知道它说’==’不能和整数一起使用,但是我在网上看到的所有内容以及我class上的幻灯片都使用它,所以我被卡住了。 代码是不完整的,我不想让它运行,我只是想解决问题。 非常感谢任何帮助,谢谢: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这样的数字是否等于“更高”是什么意思?
答案是它没有意义; 这是语言不允许的原因之一。
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. */ }
您可以通过将数字转换为字符串来强制进行比较:
if (answer.ToString() == "higher")
但是这种情况永远不会得到满足,因为没有可以转换为文本“hello”的int
值。 if
块内的任何代码都将保证永远不会执行。 你也可以写if (false)
。
为什么要将整数与字符串进行比较? 高只是一个字符串,不能变成一个只有一个数字的整数。
但我认为你可能也想要的是ToString()
用法:
int x = 5; string y = x.ToString(); Console.WriteLine(y);