2016-04-24 36 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);