如何计算对此函数的递归调用以及对它的正确答案???????
int func(x,y)
{
if (x % y == 0) return y;
x = x % y;
return func(y,x);
}
我需要一个公式或一个解释或一般表达,因为它真的很混乱?????
答案 0 :(得分:2)
使用全局变量是一个简单的解决方案。
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);
}
答案 1 :(得分:0)
首先你的代码不会编译。您需要提供x
或y
类型int
和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
}
答案 2 :(得分:0)
您如何知道通话次数?
嗯,有两种方法。
检测代码:添加一个计算到函数顶部的变量,当函数完成时,打印计数。
自行处理代码:假装是计算机,计算每个步骤并遵循决策路径。为各种输入执行此操作,并查看它为您提供的结果。计算所需的步数。请记住要考虑返回的位置 - 递归函数返回自身。
如何找到正确的答案?
与上述类似。
答案 3 :(得分:0)
我会将你的功能改为:
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
顺便说一下,你也可以使用全局变量,但这不是最佳体验,所以最好再将一个参数传递给函数。