MultiDimensional Array中所有产品的总和

时间:2015-12-15 13:42:18

标签: c# multidimensional-array sum

我想知道如何对多维数组中的所有数据求和。

这是我的add函数,用于对多维数组中的所有数据求和。

private int sum2D(int[,] week)
    {
        int sum = 0; 

        foreach (int d in week)
            sum += d;

        return sum;
    }

这只返回零金额,我很好奇为什么它不起作用,这是我的数组:

int[,] week = new int[4, 5];

这就决定了我的数组中的值:

for (int Row = 0; Row < week.GetLength(0); Row++)
                {
                    if (Row == 0)
                    {
                        Week = "Week 1  ";
                    }
                    else if (Row == 1)
                    {
                        Week = "Week 2  ";
                    }
                    else if (Row == 2)
                    {
                        Week = "Week 3  ";
                    }
                    else if (Row == 3)
                    {
                        Week = "Week 4  ";
                    }
                    Output += "\r\n" + Week + ": ";
                    for (int Col = 0; Col < week.GetLength(1); Col++)
                    {
                        if (Col == 0)
                        {
                            Day = "Monday";
                        }
                        else if (Col == 1)
                        {
                            Day = "Tuesday";
                        }
                        else if (Col == 2)
                        {
                            Day = "Wednesday";
                        }
                        else if (Col == 3)
                        {
                            Day = "Thursday";
                        }
                        else if (Col == 4)
                        {
                            Day = "Friday";
                        }

                        string value = Microsoft.VisualBasic.Interaction.InputBox("Enter the amount of products made on " + Day + " for " + Week, "Product Amount");
                        Output += "   ";
                        Output += Int32.Parse(value) + "      ";
                        txtOutput.Text = Output;
                    }

1 个答案:

答案 0 :(得分:1)

我认为你需要在内循环中设置数组中每个条目的值:

for (int Col = 0; Col < week.GetLength(1); Col++)
{
    // ...

    week[Row, Col] = Convert.ToInt32(value);
}

假设您的value是一个数字,其中包含特定一周内特定日期交易/生产的产品数量。