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

如何将计算价格重量比的数组迭代函数改写为递归实现

递归实现价格重量比数组的方案

实现思路

以数组索引作为递归递进变量,每轮递归仅计算当前索引对应的单条价格重量比,写入结果数组后进入下一轮递归,直到所有索引处理完成后终止递归,完全符合你逐次存储单条比值的需求。

推荐实现(辅助函数版,逻辑更清晰)

该版本和原有函数的入参、返回值完全兼容,调用方无需修改任何代码:

// 对外入口函数,和原函数接口完全一致
function ratioArray(pounds, price, arrayLength) {
    float[] priceRatio = new float[arrayLength];
    // 启动递归填充逻辑,从索引0开始处理
    FillRatioRecursive(pounds, price, priceRatio, 0, arrayLength);
    return priceRatio;
}

// 递归辅助函数,负责单条比值的计算与存储
void FillRatioRecursive(float[] pounds, float[] price, float[] result, int currentIndex, int arrayLength) {
    // 递归终止条件:所有元素处理完毕
    if (currentIndex >= arrayLength) {
        return;
    }
    // 计算当前索引的比值,存入结果数组
    result[currentIndex] = (float)price[currentIndex] / (float)pounds[currentIndex];
    // 处理下一个索引
    FillRatioRecursive(pounds, price, result, currentIndex + 1, arrayLength);
}

单函数递归版本(无需额外辅助函数)

通过可选参数兼容原有调用方式,无需额外定义函数:

function ratioArray(pounds, price, arrayLength, int currentIndex = 0, float[] result = null) {
    // 首次调用时初始化结果数组
    if (result == null) {
        result = new float[arrayLength];
    }
    // 终止条件:处理完所有元素直接返回结果
    if (currentIndex >= arrayLength) {
        return result;
    }
    // 计算当前位比值
    result[currentIndex] = (float)price[currentIndex] / (float)pounds[currentIndex];
    // 递归处理下一位并返回最终结果
    return ratioArray(pounds, price, arrayLength, currentIndex + 1, result);
}

逻辑说明

  • 终止规则:当当前处理的索引等于数组长度时,结束递归,不会出现数组越界问题
  • 单次递归行为:每轮仅处理1组重量、价格数据,计算完成后直接写入结果数组的对应位置,不需要一次性返回整个数组
  • 调用兼容性:两个实现版本都可以完全替换原有迭代版本,调用方不需要修改任何传参逻辑

内容的提问来源于stack exchange,提问作者Boris

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:09:00