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

如何在C语言for循环中实现每3个元素反转计数方向的逻辑

调整思路

  • 把循环变量按每3个划分为一组,用i/3获取当前组的序号(从0开始计数)
  • 用i%3获取当前元素在组内的位置,范围为0~2
  • 偶数序号的组(第0组、第2组)沿用倒序逻辑生成3、2、1序列,奇数序号的组(第1组)用正序逻辑生成1、2、3序列

调整后完整代码

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]){
    int i, row;
    
    for(i=0; i<9; i++){
        int group = i / 3;
        int pos_in_group = i % 3;
        if (group % 2 == 0) {
            row = 3 - pos_in_group;
        } else {
            row = pos_in_group + 1;
        }
        printf("%d ",row);
    }
    printf("\n");
    return 0;
}

如果不想使用分支判断,也可以把赋值逻辑简化为三目运算单行写法:

row = (group%2 == 0) ? (3 - pos_in_group) : (pos_in_group + 1);

运行后即可得到预期输出3 2 1 1 2 3 3 2 1 。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 17:00:00