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

累计求和接近10补差值并重启的JavaScript代码修正问题

累计求和数组修正方案

需求说明

输入数组:inputArr = [2, 4, 3, 7, 8, 2, 3, 4, 9, 1];
所有元素均小于10,需生成满足以下规则的累计求和输出数组:

  • 每一步的累计值直接加入输出数组
  • 当当前累计值 + 下一个输入元素 > 10时,将10 - 当前累计值加入输出,随后从下一个元素重新开始累计

期望输出:outputArr = [2, 6, 9, 1, 7, 3, 8, 2, 3, 4, 3, 9, 1];

当前问题

修改原有代码后仅前4个元素符合预期,当前错误输出:outputArr = [2, 6, 9, 1, 7, 9, 8, 10, 3, 7, 0, 9, 10]

修正代码(JavaScript)

function generateCumulativeArray(input) {
  const output = [];
  let currentTotal = 0;

  for (const num of input) {
    if (currentTotal + num > 10) {
      // 加入与10的差值,重置累计值为当前元素并加入输出
      output.push(10 - currentTotal);
      currentTotal = num;
      output.push(currentTotal);
    } else {
      // 累加后加入输出
      currentTotal += num;
      output.push(currentTotal);
    }
  }

  return output;
}

// 测试验证
const inputArr = [2, 4, 3, 7, 8, 2, 3, 4, 9, 1];
console.log(generateCumulativeArray(inputArr));
// 输出:[2, 6, 9, 1, 7, 3, 8, 2, 3, 4, 3, 9, 1]

修正逻辑说明

  1. 用currentTotal跟踪当前累计值,output存储结果数组
  2. 遍历每个输入元素时,优先判断累加当前元素是否会超过10:
    • 若超过:先补全到10的差值到输出,再把当前元素作为新的累计起点加入输出
    • 若不超过:直接累加后将新的累计值加入输出
  3. 遍历完成后直接返回结果,无需额外处理末尾元素

内容的提问来源于stack exchange,提问作者Imran Al Rashid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 05:45:44