2014-11-22 16 views
-1

我完全是C#的新手,我完全失去了。我需要做的是儘可能多地輸入數字並繼續輸入,但是當輸入值爲「0」時,即將所有輸入的數字全部加起來。在C#中輸入0時,添加輸入的數字的總和?

這是我的計劃:

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

namespace Activity2 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

      int n, sum, x = 0; 

      do 
      { 
       Console.WriteLine("Enter a Number: "); 
       n = int.Parse(Console.ReadLine()); 


      } 
      while (n != 0); 

      { 

       sum = n + x; 
       x = n; 
       n = sum; 
       Console.WriteLine("The sum is: " + n); 

      } 
      Console.ReadLine(); 
     } 
    } 

} 
+2

您可能會考慮隨時添加它們,並在輸入'0'時打印總數。 – frasnian 2014-11-22 15:48:45

回答

2

一些建議:

  • while環比do..while環一個更好的做法。
  • 您應該使用int.TryParse方法進行輸入驗證。
  • 你應該計算循環內數字的總和。
  • 只能使用兩個int變量解決問題:編號爲n,編號和爲sum

例如,你可以用下面的代碼解決您的問題:

static void Main(string[] args) 
{ 
    int sum = 0; 
    while (true) 
    { 
     Console.WriteLine("Enter a Number: "); 
     int n; 
     if (int.TryParse(Console.ReadLine(), out n)) 
     { 
      if (n == 0) 
       break; 
      sum += n; 
     } 
    } 
    Console.WriteLine("The sum is: " + sum); 
} 
+1

嗯,這是正確的,但應該在這裏建議更好地處理用戶輸入。 (Int32.TryParse)。你應該真的添加解釋而不僅僅是代碼。 – Steve 2014-11-22 15:55:31

+1

@Steve,我加了TryParse的支票。 – AndreyAkinshin 2014-11-22 15:57:53

-1

你外面打印和while循環。

sing System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace Activity2 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

      int n, sum, x = 0; 

      do 
      { 
       Console.WriteLine("Enter a Number: "); 
       n = int.Parse(Console.ReadLine()); 


      } 
      while (n != 0); 
      { 

       sum = n + x; 
       x = n; 
       n = sum; 


      } 
      Console.WriteLine("The sum is: " + n); 
      Console.ReadLine(); 
      } 
    } 

} 
+1

它已經不在do-while循環中。 – 2014-11-22 15:58:44

0

你可以簡單地用do ... while ... loop來做到這一點。

private static void Main(string[] args) 
{ 
    int n, sum = 0; 
    do 
    { 
     Console.WriteLine("Enter a number:"); 
     n = Convert.ToInt32(Console.ReadLine()); 
     sum += n; 
    } while (n != 0); 
    Console.WriteLine("Sum is:"+sum); 
    Console.ReadKey(); 
} 

ConvertToInt32()是一種將字符串轉換爲int32(int)的方法。