2017-02-08 63 views
1

我又写道在C#下面的代码,它说不能ulong类型隐式转换为INT我能做些什么来纠正,为什么会出现这种情况C#。不能隐式转换的int ULONG

Random rnd = new Random(); 

     ulong a; 
     ulong input; 
     int c1 = 0; 
     int c2; 

     a = (ulong)rnd.Next(1, 101); 

     Console.WriteLine("Welcome to the random number checker.\n" 
      +"You can guess the number. Try and find in how many tries you can get it right. " 
      +"\n\t\t\t\tGame Start"); 

     do 
     { 
      Console.WriteLine("Enter your guess"); 
      input = Console.ReadLine(); 
      c1 = c1 + 1; 
      c2 = c1 + 1; 
      if (input == a) 
      { 
       Console.WriteLine("CONGRATZ!!!!.You got that correct in "+c1 
        + "tries"); 
       c1 = c2; 

      } 
      else if (input > a) 
      { 
       Console.WriteLine("You guessed the number bit too high.try again "); 
      } 
      else 
      { 
       Console.WriteLine("You guessed the number bit too low "); 
      }; 
     } while (c1 != c2); 

每当我删除do{}部分上面的程序工作正常,但我添加它显示了这个问题。

+1

行'input = Console.ReadLine();'根本不应该编译; 'Console.ReadLine()'返回一个'string',而不是'ulong'。 – wablab

+1

由于'ulong'是* unsigned *和'int'是* signed *,因此不清楚如何转换* negative *值。你真的想要'超长',而不是'长'吗? –

+1

对不起,但我不相信你这个错误出现在你显示的代码片段中,因为没有任何赋值或类似从'ulong'到'int'的那个。 _但是你有一些其他的错误:'Console.ReadLine()'返回一个'字符串'而不是'ulong',所以你不能分配它'input'。 –

回答

0

我编译代码只有一个错误:

Cannot implicitly convert type 'string' to 'ulong' 

在行

input = Console.ReadLine(); 

如果将其更改为:

input = Convert.ToUInt64(Console.ReadLine()); 

一切都会好起来

0

input = Console.ReadLine();是问题所在。该方法返回string,但您的input被声明为ulong。如果您希望用户输入数字值,则需要尝试解析它,并在不可能的情况下报告错误。你可以这样做

Console.WriteLine("Enter your guess"); 

      if (!ulong.TryParse(Console.ReadLine(), out input)) 
      { 
       Console.WriteLine("Please enter numerical value"); 
       Environment.Exit(-1); 
      } 
0

问题是在这里:input = Console.ReadLine()ReadLine返回字符串,因此无法将其保存为ulong类型。你应该这样做:

ulong input; 
    if (ulong.TryParse(Console.ReadLine(), out ulong) 
    { 
     input = input * 2; 
    } 
    else 
    { 
     Console.WriteLine("Invalid input!"); 
    } 
相关问题