且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

这段代码是什么意思

更新时间:2022-06-20 04:07:31

现在,因为这看起来像是一项家庭作业,所以我没有给出任何线索.我相信您会自己找到答案的.这里有一些提示.

因此,如果b等于1,则fun返回a.您肯定已经知道了很多.

如果b等于2,fun会调用自身(是的是一个递归函数)并计算出a的fun(a,2-1),正如我们在上面看到的那样.然后添加a,因此fun的外部调用将返回2 * a.

现在尝试弄清楚如果用b == 3,4来调用fun会发生什么情况.您肯定会看到,这将导致什么.

干杯!
Now as this looks like a homework assignment, I am not giving away the clue. I am sure you will find the answer just by yourself. Here a couple of hints on the way.

So, if b is equal to 1, fun returns a. So much you have certainly figured.

If b is equal to 2, fun calls itself (yes it is a recursive function) and calculates fun (a, 2-1) which is a, as we saw above. Then it adds a, and hence the outer call of fun returns 2 * a.

Now try to figure what''s going on if you call fun with b == 3, 4 ... You certainly see, what this leads up to.

Cheers!


这就是谁给我嘘声??"面试中经常丢掉的大量代码.弄清楚它正在做什么的***方法之一是对其进行重构,使其更具可读性(即使在纸上也是如此).一次通过给了我这个:
This is the sort of "who gives a sh*t??" lump of code that''s often chucked at you during interviews. One of the best ways of working out what it''s doing is to refactor it so it''s more readable (even on a bit of paper). One pass through gave me this:
#include<iostream>
 
int fun( int a, int b )
{
    return a + (b == 1 ) ? 0 : fun( a, b - 1 );
}

int main()
{
    std::cout << "the result is" << fun( 3, 5 );
    char wait_for; std::cin >> wait_for;
}


当您这样做时,递归函数看起来要简单得多.要分析其作用,(a)确定递归在何处终止,(b)备份调用堆栈,以累积每个调用已完成的操作.如果这样做的话,您就不需要在很多情况下空运行代码,因为一旦知道调用多少,就可以很明显地看到正在发生的事情.

顺便说一句,重构理解"技术非常适合找出您从未见过的代码,并且可以提高代码质量.什么不喜欢?

干杯,


When you do that the recursive function looks a lot simpler. To analyse what it does (a) work out where the recursion terminates and (b) work back up the call stack accumulating what each call has done. If you do that you won''t need to dry run the code in a lot of cases as it''s fairly obvious what''s happening as soon as you know how many calls it makes.

Incidentally the "refactor to understand" technique is great to work out what code you''ve never seen before does AND it improves the quality of it. What''s not to like?

Cheers,

Ash