假设我想制作一个程序,我有7个标记为a,b,c,...,g的花盆。在每个锅中有2个种子。现在我手里拿着8颗种子,我必须在每个锅里放一粒种子。请注意,我们有7个花盆,在每个花盆里放种子之后,我手里还剩下1粒种子,那个种子我必须把它放在花盆里。那么如何使用数组呢?
我已经完成了直到第7局,如何让它回到第一个底池?
int house[8] = {2, 2, 2 ... 2};
for(int i = 1; i < 8; i++) {
hand--; // seed in hand
house[i + 7]++; // seed increases in each pot
if (i == 6) {
house[7]--;
}
printout();
}
答案 0 :(得分:2)
简单地做你想做的事。
#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;
}
要返回第一个底池,您可以使用模数
next_pot = (next_pot + 1) % POT_NUM;
或条件。
next_pot++;
if (next_pot >= POT_NUM) next_pot = 0;