2017-03-25 4 views
-1

私はC#を学ぶ最初の週です。 以下のコードで2の代わりに1の "While()"条件を使用する方法があるはずです。コードを簡素化する(初心者向け)

/* ask the user to guess a number. 
     any number between 10 and 20 is the RIGHT choice, 
     any other number outside of that scope is WRONG. */ 
     int num; 
     Console.WriteLine("[Q] Quit or make your choice"); 
     string answer = Console.ReadLine(); 
     if (answer == "Q" || answer == "q") 
      Console.WriteLine(); 
     else 
     { 
      num = Convert.ToInt32(answer); 
      while (num < 10) 
      { 
       Console.WriteLine("Wrong, try again"); 
       num = Convert.ToInt32(Console.ReadLine()); 
      } 
      while (num > 20) 
      { 
       Console.WriteLine("Wrong, try again"); 
       num = Convert.ToInt32(Console.ReadLine()); 
      } 

      Console.WriteLine("Your number is {0} and it's RIGHT", num); 
      Console.ReadKey(); 
     } 
+1

if条件が早くなります。 whileの条件で同じことをしてください。 – JJJ

+0

それで簡単!ありがとう! While()の中で&&を使って苦労しましたが、それは私に予期しない結果をもたらしました。 – Gusto

+0

これはhttp://codereview.stackexchange.com/に属します – GSerg

答えて

1

あなたは両方の条件を組み合わせることOR演算子を使用することができます:私のコードをより簡単にする方法はありますあなたは既にまたはオペレータ( `||`)でを使用している

/* ask the user to guess a number. 
    any number between 10 and 20 is the RIGHT choice, 
    any other number outside of that scope is WRONG. */ 

int num; 
Console.WriteLine("[Q] Quit or make your choice"); 
string answer = Console.ReadLine(); 

if (answer == "Q" || answer == "q") 
    Console.WriteLine(); 
else 
{ 
    num = Convert.ToInt32(answer); 
    while (num < 10 || num > 20) 
    { 
     Console.WriteLine("Wrong, try again"); 
     num = Convert.ToInt32(Console.ReadLine()); 
    } 

    Console.WriteLine("Your number is {0} and it's RIGHT", num); 
    Console.ReadKey(); 
} 
関連する問題