这段代码是什么意思 [英] what is the mean this code

查看:83
本文介绍了这段代码是什么意思的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>
#include<conio.h>
using namespace std;

int fun(int,int);
void main()
{
int x=3,y=5;
cout<<"the result is"<<fun(x,y);

    getch();
}
int fun(int a,int b)
{
    int box;
    if(b==1)
        return a;
    else
    return a+fun(a,b-1);
}





这是什么意思,这些句子{a + fun(a,b-1)} ??



[edit]为标题提供了可读性[/edit]





what is mean and what do this sentents { a+fun(a,b-1) }??



[edit] brought readability to title [/edit]

推荐答案

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

因此,如果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


这篇关于这段代码是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆