【问题标题】:How does this c++ function work?这个 c++ 函数是如何工作的?
【发布时间】:2018-07-17 02:56:57
【问题描述】:
#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 is: 13”。 当我做 n = 7 时,我如何得到 x = 13? 该函数似乎重复了一些次数,直到 x=1。

【问题讨论】:

  • 调试器、一些内联打印语句或函数运行的纸上简单的痕迹可以告诉你
  • 递归(n):见递归
  • @FredLarson,终止条件在哪里? :) :)
  • @RSahu:我想你可以在弄清楚后终止。 8v)
  • 也许在 F# 中看到问题会有所帮助:stackoverflow.com/questions/2845744/…

标签: c++


【解决方案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;

这个概念称为recursion,有时非常有用。您的函数当前计算第 n 个斐波那契数。

附带说明,您应该阅读为什么使用 system("PAUSE");bad idea

【讨论】:

    猜你喜欢
    • 2016-02-22
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多