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

C#循环中如何将索引序列(4,5,6,7)转换为(1,3,5,7)?

解决方案

有两种简洁的方式解决这个索引映射问题,不用手动判断:

方式一:索引转换公式

直接通过数学公式把i(4-7)转换成目标索引(1,3,5,7),公式为2*i -7,验证对应关系:

  • i=4 → 2*4-7=1
  • i=5 → 2*5-7=3
  • i=6 → 2*6-7=5
  • i=7 → 2*7-7=7

修改后的代码:

for (int i = 4; i < 8; i++) 
{
    if (!Deck1Flags[i]) continue;
           
    int reloadIndex = 2 * i - 7; // 完成索引转换
    if (ReloadTimesSec[reloadIndex] > 0f) continue;
    ...
}

方式二:换循环遍历逻辑

更直观的方式是直接遍历ReloadTimesSec需要的奇数索引,反向推导Deck1Flags的索引(目标索引+3就是对应的Deck1Flags索引:1+3=4,3+3=5,以此类推),代码可读性更强:

// 直接遍历ReloadTimesSec的目标奇数索引:1,3,5,7
for (int reloadIndex = 1; reloadIndex <= 7; reloadIndex += 2)
{
    int deckIndex = reloadIndex + 3; // 映射到Deck1Flags的索引:4,5,6,7
    if (!Deck1Flags[deckIndex]) continue;
           
    if (ReloadTimesSec[reloadIndex] > 0f) continue;
    ...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 11:05:14