【问题标题】:Sum of all products in MultiDimensional Array多维数组中所有产品的总和
【发布时间】:2015-12-15 13:42:17
【问题描述】:

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

这是我的 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;
                    }

【问题讨论】:

  • 不是new int[4, 5] 是一维数组而不是多维数组吗?
  • 你在哪里填充你的数组?
  • @tomasbasham 不,C# Language Specification 声明 “数组类型的等级由数组类型中最左边的等级说明符给出:等级说明符表示数组是一个秩为 1 的数组加上秩说明符中的“ , ”标记的数量。[…] 类型 int[][,,][,] 是一个由二维数组组成的一维数组int 的维数组。"
  • @Albireo 谢谢,这清除了它
  • sum = 0 因为你从来没有在数组中放任何东西。你只在'for'中使用它来增加Output。我不确定你想用这笔钱达到什么目的,所以你能澄清一下吗?

标签: c# multidimensional-array sum


【解决方案1】:

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

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

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

假设您的value 是一个数字,表示在给定一周内的特定日期交易/生产的产品数量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-24
    • 2021-10-08
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-23
    相关资源
    最近更新 更多