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

数组移动求和开发遇阻:无法记录当前位置实现前后移动

解决方案:维护当前位置变量解决移动位置丢失问题

问题的核心是没有持续跟踪当前所在的数组索引,每次执行指令后都要更新并保存这个位置,才能让后续指令基于正确的起点计算。以下是修正后的完整代码和关键说明:

修正后的代码

# 读取起始位置与数组
start_pos = int(input("输入起始位置: "))
arr = list(map(int, input("输入逗号分隔的数组: ").split(',')))
arr_length = len(arr)

# 初始化核心变量:当前位置(确保在数组索引范围内)、两类移动总和
current_index = start_pos % arr_length
forward_sum = 0
backwards_sum = 0

# 处理指令循环
while True:
    command = input("输入指令(或输入exit退出): ").strip()
    if command.lower() == 'exit':
        break
    
    # 解析指令格式
    cmd_parts = command.split()
    if len(cmd_parts) != 3:
        print("指令格式错误,请使用:[步数 方向 步长]")
        continue
    try:
        step_count = int(cmd_parts[0])
        direction = cmd_parts[1].lower()
        step_size = int(cmd_parts[2])
    except ValueError:
        print("步数和步长必须是整数")
        continue
    
    # 处理forward移动
    if direction == 'forward':
        total_steps = step_count * step_size
        for _ in range(total_steps):
            # 计算下一个位置,超出边界自动循环
            current_index = (current_index + 1) % arr_length
            # 累加当前位置的元素值到forward总和
            forward_sum += arr[current_index]
    # 处理backwards移动
    elif direction == 'backwards':
        total_steps = step_count * step_size
        for _ in range(total_steps):
            # 向后移动时用取模处理边界,避免负索引问题
            current_index = (current_index - 1) % arr_length
            backwards_sum += arr[current_index]
    else:
        print("无效方向,请使用forward或backwards")

# 输出最终结果
print(f"Forward移动总和: {forward_sum}")
print(f"Backwards移动总和: {backwards_sum}")

关键修正点

  1. 新增current_index变量:从起始位置初始化,每次移动后都会更新这个变量,确保后续指令的起点是上一次移动的终点。
  2. 边界循环处理:用% arr_length实现超出数组边界后的循环,无论是向前还是向后移动,都能正确定位到数组的另一端(比如向后移动到索引-1时,取模后会变成数组最后一个索引)。
  3. 总和累加逻辑:起始位置不计入总和,只有每次移动后到达的新位置的元素才会被累加到对应方向的总和中,符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:05:17