需要帮助将数组中的二维阵列组合成数周和平均数

时间:2016-04-27 15:01:41

标签: c#

这是我到目前为止的代码。我需要帮助组织它。

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

namespace Lab_A
{
class Activity2DArrayA
{
    static void Main(string[] args)
    {
        // initialize 2-d array to store steps & dates 
        // this array contains 4 rows (weeks) 
        // each row contains 7 columns (days)
        int[,] steps = {
            { 4835, 24794, 13827, 10470, 10210, 10310, 14868 },
            { 11384, 16781, 8090, 8565, 10666, 15162, 13828 },
            { 14246, 8416, 19782, 20617, 7700, 21225, 34826 },
            { 22881, 17980, 26924, 18568, 19299, 22164, 21992 },
        };
        int sum = 0;

        // loop thru array using nested for loop 
        // the outer loop controls the rows 
        // the inner loop controls the columns 
        for (int row = 0; row < steps.GetLength(0); row++)
        {
            //Console.WriteLine();
            Console.Write("   week  " + (row + 1) +" ");


            for (int col = 0; col < steps.GetLength(1); col++)
            {
                sum += steps[row, col];


                double average = sum / 28;
                Console.WriteLine("average: {0}", average);
                Console.WriteLine("total: {0}", sum);

我可以在第1-4周显示行,但我需要帮助,将一周中的几天添加到列中,并显示总数和平均值

1 个答案:

答案 0 :(得分:0)

对于每日平均值,您可以执行以下操作:

//declare outside of loops
var dayStepAverages 
    = new Dictionary<DayOfWeek, int>()
    {
        //this sort of initialization assumes you're using C# 6.0
        [DayOfWeek.Monday] = 0,
        [DayOfWeek.Tuesday] = 0,
        [DayOfWeek.Wednesday] = 0,
        [DayOfWeek.Thursday] = 0,
        [DayOfWeek.Friday] = 0,
        [DayOfWeek.Saturday] = 0,
        [DayOfWeek.Sunday] = 0
    };

//in inner loop
dayStepAverages[(DayOfWeek)col] += steps[row,col];

对于每周,做这样的事情:

for (int row = 0; row < steps.GetLength(0); row++)
{
    //inside of first loop
    var weeklyTotal = 0;
    for (int col = 0; col < steps.GetLength(1); col++)
    {
        //inner loop
        weeklyTotal += steps[row, col];
    }
    var averageForWeek = weeklyTotal / 7;
    //store averageForWeek in a list or something.
}