2016-04-24 35 views
0

我有一個簡單的程序在我的c#類中寫入,我無法弄清楚最後一部分。我必須在列中寫出所有從0到20的偶數,然後再有另一列平方值和多一列立方體值。我已經掌握了所有的工作。然後我最後需要每列的總和,但似乎無法弄清楚。如何獲得c#中一列數字的總和

任何幫助,將不勝感激。我的代碼包含在下面。

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

namespace COMP2614Assign01 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     string formatStringHeading = "{0,5} {1, 10} {2, 10:N0}"; 

      Console.WriteLine(formatStringHeading 
       ,"number" 
       ,"square" 
       ,"cube" 
       ); 
     Console.WriteLine(new string('-', 28)); 

     int e = 0; 

     while (e <= 20) 
     { 
      int e1 = e * e; 
      int e2 = e * e * e; 
      Console.WriteLine(formatStringHeading 
       ,e 
       ,e1 
       ,e2); 
      e += 2; 
     } 
     Console.WriteLine(new string('-', 28)); 


    } 
} 

}

+0

循環添加三個變量之前保持的總和,sumSquared和sumCube,循環內部添加E,E1,E2的值,外循環打印出來 – Steve

回答

0
int e = 0; 
int eSum = 0, e1Sum = 0, e2Sum = 0; 

while (e <= 20) 
{ 
    eSum += e; 
    int e1 = e * e; 
    e1Sum += e1; 
    int e2 = e * e * e; 
    e2Sum += e2; 
    Console.WriteLine(formatStringHeading 
     ,e 
     ,e1 
     ,e2); 
    e += 2; 
} 
Console.WriteLine(new string('-', 28)); 
Console.WriteLine(formatStringHeading 
    ,eSum 
    ,e1Sum 
    ,e2Sum);