我如何计算对这个函数的递归调用以及它的正确答案是什么??????
int func(x,y)
{
if (x % y == 0) return y;
x = x % y;
return func(y,x);
}
我需要它的公式或解释或一般表达式,在这里真的很困惑??????
我如何计算对这个函数的递归调用以及它的正确答案是什么??????
int func(x,y)
{
if (x % y == 0) return y;
x = x % y;
return func(y,x);
}
我需要它的公式或解释或一般表达式,在这里真的很困惑??????
使用全局变量是简单的解决方案。
int i;
main()
{
i=0; //if you want to avoid main call just start with i=-1
//if you are using loop and then calling function in loop ,
//make i value zero or -1 to know how many recursive calls are made to particular call.
func(x,y);
//now i consists number of recursive calls made.
}
int func(int x,int y)
{
i++;
if (x % y == 0) return m;
x = x % y;
return func(y,x);
}
我会将您的功能更改为:
int func(int x, int y, int& n)//I asume x and y are ints
{
if (x % y == 0) return y;
x = x % y;
return func(y,x, n+1);//not sure if I understood question correctly, so I think you need to change n value here.
}
int func(int x, int y, int& n)//I asume x and y are ints
{
++n;//not sure if I understood question correctly, it may be you need this place for count variable increment
if (x % y == 0) return y;
x = x % y;
return func(y,x, n);
}
要使用该功能,您将需要:
int x = 1000, y = 7, n = 0;
int ret = func(x, y, n); //n must be zero
顺便说一句,你也可以使用全局变量,但这不是最好的体验,所以最好再向函数传递一个参数。
怎么知道来电次数?
嗯,有两种方法。
检测代码:添加一个计数到函数顶部的变量,当函数完成时,打印计数。
自己走代码:假装是电脑,计算每一步,走决策路径。对各种输入执行此操作,看看它会给您带来什么结果。计算它所走的步数。请记住要考虑您要返回的位置 - 递归函数返回到自身。
如何找到正确答案?
与上面类似。
首先,您的代码将无法编译。您需要给出x
和y
类型,例如int
or long
。x
其次,您可能想y
在您做任何其他事情之前订购。就像是:
int func(int x, int y) {
int mx = max(x, y);
int mn = min(x, y);
// as above with mx for x and mn for y
}