2017-01-18 7 views
0

私は問題があります。私は実践のためのコンソールアプリケーションを書いた。プログラムは数字を入力するよう繰り返しユーザーに要求し、プログラムは数字を加算し、ユーザーが「done」と入力すると、プログラムは入力された数字と合計を分けます。変数スコープtrought If/elseブロックの場合

私の問題は次のとおりです。あなたは私が変換された宣言= int.Parse(入力);を宣言しなければならなかったので、プログラムは準拠していません。 else節に変換されたintを宣言しているので、else節には、else節に変換されるため、プログラムは最初の2つの選択肢をスキップして文字列を数値に変換します。もし、存在しないならば。

私は変数スコープのために同じブラケットにすべてを入れなければならないことを知っていますが、どうですか?

bool keepGoing = true; 
int total = 0; 

//The loop begins, repeatedly asks the user for numbers. 
while (true) 
{ 

    //Asks the user for numbers . 
    Console.Write("Type a number:"); 
    string input = Console.ReadLine(); 

    // When user types in quit the program quits 
    if (input == "quit") 
    { 
     break; 
    } 


    // When user types "done", dividing total with converted(entered numbers). 
    else if (input == "done") 
    { 
     total /= converted; 
     Console.WriteLine(total); 
     continue; 
    } 

    // If user types a number, convert into integer and add total and converted together. 
    else 
    { 
     try 
     { 
      int converted = int.Parse(input); 
      total += converted; 
      Console.WriteLine(total);    
     } 

     // Tells the user to type again. 
     catch (FormatException) 
     { 
      Console.WriteLine("Invalid Input, please type again"); 
     } 
    } 
} 
+0

*プログラムは、入力された番号の合計がそれはあなたのプログラムは、あなたが考えてきた何をしようとしたかのように思えません*分割します。最高でも、合計を*最後に入力した数値で割ります。それは意図された行動ですか? –

+0

あなたは正しいです、私はちょうど私の間違いを認識しました:)私は、入力された数字を追​​跡する必要がありますか?私は別の変数を作成し、ユーザーが数値を入力するたびに+1を与え、それを合計で割りますか? – Ryanoz

+0

私には合理的なサウンド:) –

答えて

0

完全なコードブロックは、ここで与えられた - >

int total = 0; 
    int converted = 0; 

    //The loop begins, repeatedly asks the user for numbers. 
    while (true) 
    { 

     //Asks the user for numbers . 
     Console.Write("Type a number:"); 
     string input = Console.ReadLine(); 

     // When user types in quit the program quits 
     if (input == "quit") 
     { 
      break; 
     } 


     // When user types "done", dividing total with converted(entered numbers). 
     else if (input == "done") 
     { 
      total /= converted; 
      Console.WriteLine(total); 
      continue; 
     } 

     // If user types a number, convert into integer and add total and converted together. 
     else 
     { 
      try 
      { 
       converted = int.Parse(input); 
       total += converted; 
       Console.WriteLine(total); 
      } 

      // Tells the user to type again. 
      catch (FormatException) 
      { 
       Console.WriteLine("Invalid Input, please type again"); 
      } 
     } 
    } 
関連する問題