[英]How does this c++ function work?
#include <cstdlib>
#include <iostream>
using namespace std;
int myFunction(int n)
{
int x;
if (n==1 || n==2)
x = 1;
else
x = myFunction(n-2) + myFunction(n-1);
return x;
}
int main(int argc, char *argv[])
{
int n,a;
n = 7;
a = myFunction(n);
cout << "x is: " << a;
system("PAUSE");
return EXIT_SUCCESS;
}
此輸出為“ x是:13”。 當我做n = 7時,如何得到x = 13? 似乎函數重復了幾次直到x = 1。
我將為您介紹一個簡單的示例,其中函數為4,但是總體概念對於7也相同。
首先調用: myFunction(4)
並在函數n = 4
。
由於n
不等於1或2,我們跳到else:
x = myFunction(3) + myFunction(2);
x = myFunction(1) + myFunction(2) + 1; // If there is a 1, that means
// that we went to the if
// clause, not the else, since
// n was either 1 or 2
x = 1 + 1 + 1;
x = 3;
這個概念稱為遞歸 ,有時可能非常有用。 您的函數當前計算第n個斐波那契數。
附帶說明一下,您應該閱讀為什么使用system("PAUSE");
是個好主意 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.