我正在编写一个程序,我想到了一个数字,然后计算机猜测了它。我一边尝试一边测试它,但我不断收到不应该出现的错误。错误是主题标题。我使用 Int.Parse 来转换我的字符串,但我不知道为什么会收到错误。我知道它说“==”不能与整数一起使用,但我在网上看到的所有内容以及我课堂上的幻灯片都使用它,所以我被困住了。代码不完整,我还不想让它运行,我只是想解决问题。我非常感谢任何帮助,谢谢: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")
您要求一个数字,但您试图将其与非数字数据进行比较。忘记语言语义,你期望如何比较number to text?问像 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")
但这个条件永远不会遇见因为有no int
将转换为文本“hello”的值。里面的任何代码if
块将保证永远不会执行。你不妨写if (false)
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)