2017-02-08 65 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!"); 
    } 
相關問題