You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#编写递归函数替代嵌套循环实现数组求和

四维数组递归求和实现方法

要把嵌套循环的四维数组求和改成递归实现,核心思路是逐层遍历数组维度:每一层递归负责处理当前维度的所有索引,当走到最后一个维度时直接累加元素,否则递归进入下一个维度继续处理。

以下是C#的实现代码:

using System;

class Program
{
    static void Main()
    {
        int[,,,] exampleArray = new int[1, 2, 3, 4];
        // 可自行给数组赋值测试,比如exampleArray[0,0,0,0] = 5;
        int totalSum = Sum4DArray(exampleArray, 0, new int[4]);
        Console.WriteLine(totalSum);
    }

    static int Sum4DArray(int[,,,] array, int currentDimension, int[] indices)
    {
        int sum = 0;
        int dimensionLength = array.GetLength(currentDimension);

        // 处理最后一个维度时,直接遍历累加元素
        if (currentDimension == 3)
        {
            for (int i = 0; i < dimensionLength; i++)
            {
                indices[currentDimension] = i;
                sum += array[indices[0], indices[1], indices[2], indices[3]];
            }
        }
        else
        {
            // 遍历当前维度的每个索引,递归处理下一个维度
            for (int i = 0; i < dimensionLength; i++)
            {
                indices[currentDimension] = i;
                sum += Sum4DArray(array, currentDimension + 1, indices);
            }
        }
        return sum;
    }
}

代码说明

  • Sum4DArray是递归核心方法:
    • currentDimension标记当前处理的维度(从0开始,对应原循环的i、j、k、l)
    • indices数组记录各维度的当前索引位置,每进入一个维度就更新对应位置的索引
    • 当处理到最后一个维度(索引3)时,直接遍历该维度所有元素并累加;否则递归进入下一个维度,将下层递归的求和结果累加进来
  • 初始调用时传入currentDimension=0和长度为4的索引数组,从第一个维度开始遍历

内容的提问来源于stack exchange,提问作者Furkan Şen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 01:10:27