我在 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。
IE。预增量意味着您要添加额外的 10。