Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/163.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在数组中循环_C++_Arrays - Fatal编程技术网

C++ 在数组中循环

C++ 在数组中循环,c++,arrays,C++,Arrays,假设我想做一个程序,其中,我有7个罐子,标记为罐子a,b,c,…,g。每个花盆里有2粒种子。现在我手里有8粒种子,我必须在每个花盆里放1粒。注意,我们有7个罐子,在每个罐子里放一粒种子后,我手上还剩下1粒种子,我必须把它放在罐子a上。那么如何使用数组来实现这一点呢 我一直做到第七壶,如何让它回到第一壶 inthouse[8]={2,2,2…2}; 对于(int i=1;i

假设我想做一个程序,其中,我有7个罐子,标记为罐子a,b,c,…,g。每个花盆里有2粒种子。现在我手里有8粒种子,我必须在每个花盆里放1粒。注意,我们有7个罐子,在每个罐子里放一粒种子后,我手上还剩下1粒种子,我必须把它放在罐子a上。那么如何使用数组来实现这一点呢

我一直做到第七壶,如何让它回到第一壶

inthouse[8]={2,2,2…2};
对于(int i=1;i<8;i++){
手--;//手里拿着种子
house[i+7]++;//每盆种子数量增加
如果(i==6){
众议院[7]-;
}
打印输出();
}

只需做你想做的事

#define POT_NUM 7

int main(void) {
    int seeds_in_hand = 8;
                               /* a, b, c, d, e, f, g */
    int seeds_in_pots[POT_NUM] = {2, 2, 2, 2, 2, 2, 2};

    int next_pot = 0;
    while (seeds_in_hand > 0) {
        /* put a seed from the hand to a pot */
        seeds_in_hand--;
        seeds_in_pots[next_pot]++;
        /* move on the next pot */
        next_pot = (next_pot + 1) % POT_NUM;
    }

    return 0;
}
要返回到第一个pot,可以使用模运算

next_pot = (next_pot + 1) % POT_NUM;
或条件

next_pot++;
if (next_pot >= POT_NUM) next_pot = 0;

首先,停止访问数组范围之外的对象,否则将调用未定义的行为。只有
inthouse[0]
house[7]
可以申报
inthouse[8]