2016-12-01 4 views
1

これまでは、ランダムに生成された数字とユーザー入力の違いを見つけるのに苦労しました。私はちょっとした検索をして、を使うことができず、実際にはこれを使用しなければならないことがわかりました。int guess = Convert.ToInt32(Console.ReadLine());私は偶然、それをConvert.ToInt32(Console.Read());としました。私が自分自身を効果的に説明していないなら、私はコーディングに新しい人で、これは学ぶべきものであることを意味しました。ありがとう!誰かがなぜintに変換し、Readの代わりにread lineを使って私の問題を修正したのか説明できますか?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading; 
using System.Threading.Tasks; 

namespace ConsoleApplication2 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.WriteLine("Would you like to play the guessing game?"); 
      string input = Console.ReadLine(); 

      if (input.Equals("yes")) 
      { 
       Console.WriteLine("Alright! The rules are simple, i'll think of a number and you guess it!"); 
       Console.WriteLine("Alright enter your guess: "); 


       int guess = Convert.ToInt32(Console.ReadLine()); 


       Random rand = new Random(); 
       int answer = rand.Next(1,11); 

       if (rand.Equals(guess)) 
       { 
        Console.WriteLine("Congratulations you guessed correctly!"); 
       } 
       else 
       { 
        Console.WriteLine("Aww you were so close! I guessed " + answer); 
        int difference = guess - answer; 
        Console.WriteLine("you were only " + Math.Abs(difference) + " away"); 
       } 

      } else 

      { 
       Console.WriteLine("Closing application..."); 
       Thread.Sleep(1000); 
       Environment.Exit(0); 
      } 
     } 
    } 
} 

答えて

0
Console.Read() 

戻ります入力された単一の文字のASCII 値。

たとえば、「A」を入力すると65が返されます。 ASCIIコードのリストについては、hereを参照してください。 1のASCII値は実際には49です。

Convert.ToInt32(Console.ReadLine()); 

行全体を読み取り、整数に変換しようとします。

+0

甘い、私はASCII値についても考えなかった。ありがたいことに私はあなたがハハについて話していることを知っています。 – Zech

0

Console.Readは、()()1つの文字とConsole.ReadLineをつかむことが押された「Enter」キーを発見したユーザーの種類まで、行全体またはすべてをとります。

0

Becuase Console.Readはコンソールから文字を読み込みます。これは整数として返されます。したがって、「yes」と入力すると、出力は

121 = y 
101 = e 
115 = s 
13 = 
10 = 

になります。最後の2文字(13と10)は、Windowsの改行文字と同じです。

関連する問題