如何计算对该函数的递归调用,以及正确答案是什么
How can I calculate the recursive calls to this function and what will be the correct answer to it?
如何计算对此函数的递归调用,正确答案是什么??????
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);
}
首先,您的代码不会编译。您需要提供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
}
你是怎么知道电话号码的?
有两种方法。
-
插入代码:添加一个计数到函数顶部的变量,当函数完成时,打印计数。
-
自己执行代码:假装是计算机,计算每一步并遵循决策路径。对各种输入进行此操作,看看它会给您带来什么结果。计算它所走的步数。请记住,要考虑返回到的位置-递归函数返回到自身。
如何找到正确答案?
与上面类似。
- 运行代码并打印结果
- 遍历代码,弄清楚每一步的结果是什么,以及最终结果是什么
我会将您的函数更改为:
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
顺便说一句,你也可以使用全局变量,但这不是最好的体验,所以最好再给函数传递一个参数。
相关文章:
- 是什么让放置新调用对象的构造函数?
- 使用基类指针调用基类的值构造函数的语法是什么?
- C++:使用方法调用析构函数的顺序是什么?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 使用动态链接加载程序 <dlfcn.h> 而不是直接函数调用的目的是什么?
- "noexcept-expression 由于对......的调用而计算为'假'"是什么意思?
- 正确的方法是什么?调用指针到指针到指针内部的函数?
- 调用boost.asio的异步函数时,线程是什么时候创建的
- C++:允许临时对象调用非常量成员函数的设计理念是什么?
- 是什么能让dynamic_cast开始抛出 std:bad_cast 即使被调用在指针上?
- 在 MySQL 连接器C++ API 中使用一个函数调用执行多个查询的正确方法是什么?
- 以下声明C++中调用的函数的方法是什么?
- 使用 std::async 调用模板函数的正确方法是什么?
- 在C++中将结构从被调用函数返回到调用函数的适当方法是什么
- 调用不属于基类的派生类函数的最佳方法是什么?
- {}在函数调用中的参数之前是什么意思?key_equal {}(key1,key2);
- 调用模板化类内的枚举类枚举器的正确语法是什么
- DLL 的"good"调用约定是什么?
- 当我们在MSDN中调用UpdateWindows()时,该方法是什么
- 从malloc()进行的Windows和Linux本机OS/系统调用是什么