2017-02-08 2 views
1

에 INT 변환 할 수 없습니다 나는 C#에서 다음 코드를 worte 그리고 암시 적으로 내가 해결하기 위해 무엇을 할 수 있는지 INT에 ulong 형식을 변환 할 수 없다고 그리고 난 그 do{} 부분을 제거 할 때마다 이유는C#. 암시 적 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); 

을 발생 않았다 상단 프로그램은 잘 작동하지만 내가 추가하는 것은 그 문제를 보여줍니다. 당신이 그것을 변경하는 경우

라인에서
Cannot implicitly convert type 'string' to 'ulong' 

input = Console.ReadLine(); 

:

+1

'input = Console.ReadLine();'줄은 전혀 컴파일하면 안됩니다. 'Console.ReadLine()'은'ulong'이 아닌'string'을 반환합니다. – wablab

+1

'ulong'이 * unsigned *이고 int가 * signed *이기 때문에 * 음수 * 값을 어떻게 변환하는지 불분명합니다. 당신은 정말로 'ulong'을 원하지, 'long'을 원하지 않습니까? –

+1

죄송 합니다만, 나는이 오류가 여러분이 보여주는 코드 스 니펫에 나타나지 않는다고 생각합니다. 왜냐하면 할당이나 "ulong"에서 "int"에 이르기까지 아무 것도 없기 때문입니다. _But_ 다른 버그가 있습니다 :'Console.ReadLine()'은''ulong'이 아닌'string'을 반환하므로'input'을 할당 할 수 없습니다. –

답변

0

난 당신의 코드를 컴파일 할 단 하나의 오류가

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

모든 것이 잘 될 것입니다

0

input = Console.ReadLine();이 문제입니다. 이 메서드는 string을 반환하지만 inputulong으로 선언됩니다. 사용자가 숫자 값을 입력 할 것으로 예상하는 경우 구문 분석을 시도하고 가능한 경우 오류를보고해야합니다. 이렇게 할 수 있습니다.

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!"); 
    }