2016-09-10 12 views
-1

私は、ポットa、b、c、...、gという7つのポットがある場所でプログラムを作りたいとしましょう。各ポットには2つの種があります。今私は私の手に8種の種子を持っています。そこでは、それぞれの種子に1種の種子を入れなければなりません。私たちが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(); 
} 
+1

まず、範囲外の配列へのアクセスを停止するか、*未定義の動作*を呼び出します。 'house [0]'〜 'house [7]'のみが 'int house [8]'宣言のために利用可能です。 – MikeCAT

答えて

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;