gpt4 book ai didi

c - 从中间然后开始迭代数组

转载 作者:行者123 更新时间:2023-11-30 18:37:15 25 4
gpt4 key购买 nike

我想从靠近中间的索引开始迭代任何数组,走到末尾,然后转到开头。
举个例子:

#include <stdio.h>

int main(){


int a[]= {1, 2, 3, 4, 5, 6, 7,};

int i = 0;

for (i = 2; i < 6; i++){

if (i == 6){
i = 0;

}

printf("%d\n", a[i]);
}

return 0;
}

当索引到达末尾(索引 6)时,如何将索引“重新分配”为零

最佳答案

这是一个简单的记录。未经测试,因此请根据需要进行调整。这个想法是让计数器从 0 开始,并使用模数每次添加开始值以使其相对。

int a[]= {1, 2, 3, 4, 5, 6, 7};

int length = sizeof(a)/sizeof(a[0]);
int start = length/2;

for (int i = 0; i < length; i++)
{
printf("%d\n", a[(i+start)%length]);
}

并支持@SouravGhosh 在我得到这个答案之前在评论中指出模数。

关于c - 从中间然后开始迭代数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37947103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com