2015-06-25 34 views
0

這是我的代碼。我想讓用戶連續輸入任意數量的雙打,直到100次(但可以是用戶想要的次數但少於100次)。顯示所有輸入值的總和。在我的代碼中,我不知道如何讓用戶連續輸入數字(即時猜測你會有一個while循環)。 非常感謝!添加每個雙位數字的數字

Console.WriteLine("Enter double"); 
    double.first = double.Parse(Console.ReadLine()); 

    while(first != 0) 
    { 
     Console.WriteLine("Enter double"); 
     int num = int.Parse(Console.ReadLine()); 
     double sum; 
     while(num != 0) 
      { 
      double ten = num/10; 
      double tenth = Math.Floor(ten); 
      double oneth = num % 10; 
      sum = tenth + oneth; 
      Console.WriteLine("{0}", sum); 
      break; 

      } 

     first = double.Parse(Console.ReadLine()); 

    } 
+0

就放在'while'陳述一個破發點,並通過它一步。此外,請查看['break break'](https://msdn.microsoft.com/en-us/library/adbctzc4.aspx)(與斷點完全不同)。 –

+1

這是一項家庭作業嗎? – Kevin

+0

目前還不清楚你在問什麼。當我閱讀「顯示單獨和一起輸入的所有值的總和」時,我認爲你想總結所有輸入的雙打(一起),並且要總結每個輸入的雙倍(單獨)的數字。這是你問的嗎? – Shar1er80

回答

1

評論後編輯:

好吧,我還是假設這是功課,但這裏是一些最基礎...

我會做這兩個階段,數據輸入,然後calcualtion。

創造一些存儲在輸入和循環

var inputs = new List<double>(); 
var counter = 0; 

現在到了你,而循環您輸入的反...

while(counter < 100) 
{ 
    var tempInput = 0.0D; 
    Double.TryParse(Console.ReadLine(), out tempInput); 
    if(tempInput == 0.0D) 
    { 
     // The user did not enter something that can be parsed into a double 
     // If you'd like to use that as the signal that the user is finished entering data, 
     // just do a break here to exit the loop early 
     break; 
    } 
    inputs.Add(tempInput); 
    // This is your limiter, once counter reaches 100 the loop will exit on its own 
    counter++; 
} 

現在,你可以在執行calcualtions您累計的值...

var total = 0.0D; 
foreach(var value in inputs) 
{ 
    total += value; 
} 

現在顯示總值。

請記住,有很多方法可以做到這一點,這只是一個例子,可以讓您瞭解獲取數據的問題。

1

我希望讓用戶輸入任意數量的雙打不斷,直到 100次(可能是但次數的用戶希望,但小於100 )。

您需要跟蹤3件事情。

  1. 下一個雙。
  2. 運行總數。
  3. 用戶提供了多少次輸入。

變量

double next; 
double runningTotal = 0; 
int iterations = 0; 

現在,不斷接收來自用戶的輸入,你可以寫一個while-loop你正確識別。在這個循環中,你應該檢查兩件事情:

  1. ,未來值是一個雙,它不爲0
  2. 用戶已不提供輸入超過100次。

雖然環

while (double.TryParse(Console.ReadLine(), out next) && next != 0 && iterations < 100) { 
    // Count number of inputs. 
    iterations++; 

    // Add to the running total. 
    runningTotal += next; 
} 

所有值的總和顯示進入。

只需寫入控制檯即可。

輸出:

Console.WriteLine("You entered {0} number(s) giving a total value of {1}", iterations+1, runningTotal); 

完整的示例:

static void Main() 
{ 
    double runningTotal = 0; 
    double next; 
    var iterations = 0; 

    Console.Write("Enter double: "); 
    while (double.TryParse(Console.ReadLine(), out next) && next != 0 && iterations < 100) 
    { 
     runningTotal += next; 
     iterations++; 
     Console.Write("Enter double: "); 
    } 
    Console.WriteLine("You entered {0} number(s) giving a total value of {1}", iterations+1, runningTotal); 
    Console.Read(); 
}