このコードを C と Java で実行したところ、それぞれ 65 と 55 になりました。C がどのようにして 65 を取得できるかわかりません。助けてください。
int recur(int count)
{
if(count==10)
return count;
else
return (count+recur(++count));
}
void main()
{
printf("%d\n",recur(0));
}
このコードを C と Java で実行したところ、それぞれ 65 と 55 になりました。C がどのようにして 65 を取得できるかわかりません。助けてください。
int recur(int count)
{
if(count==10)
return count;
else
return (count+recur(++count));
}
void main()
{
printf("%d\n",recur(0));
}
return (count+recur(++count));
未定義の動作です。コンパイラが異なれば、結果が異なる場合があります。コンパイル オプションが異なる同じコンパイラでも、出力が異なる場合があります。
コードを書き直し、いくつかのデバッグ ステートメントを使用してコードパッドでテストすると、何が起こっているかがわかります。コードを実行して何が起こっているのかを確認するために、このアプローチを採用することをお勧めします。
int recur(int count)
{
int ret;
if(count==10)
ret = count;
else {
printf("Count Before = %d\n", count);
ret = (count +recur(++count));
}
printf("Count after = %d\n", ret);
return ret;
}
void main()
{
printf("%d\n",recur(0));
}
それを実行すると、これが得られます
Count Before = 0
Count Before = 1
Count Before = 2
Count Before = 3
Count Before = 4
Count Before = 5
Count Before = 6
Count Before = 7
Count Before = 8
Count Before = 9
Count after = 10
Count after = 20
Count after = 29
Count after = 37
Count after = 44
Count after = 50
Count after = 55
Count after = 59
Count after = 62
Count after = 64
Count after = 65
65
したがって、最初に10まで再帰し、次に10を追加し、次に9、8などを追加することがわかります...
それを i = (count + recur(count + 1)) に変更します
与える
Count Before = 0
Count Before = 1
Count Before = 2
Count Before = 3
Count Before = 4
Count Before = 5
Count Before = 6
Count Before = 7
Count Before = 8
Count Before = 9
Count after = 10
Count after = 19
Count after = 27
Count after = 34
Count after = 40
Count after = 45
Count after = 49
Count after = 52
Count after = 54
Count after = 55
Count after = 55
55
しかし、現在、ネスティングのレベルは 10 に達しただけですが、追加された量はまだ 9 です。
すなわち。前の増分は、さらに 10 を追加していることを意味します。