采用地址传递的方式编写一个递归函数,求斐波那契数列的第N项,并调用此函数求这个数列前N项的和

如何采用地址传递的方式
编写一个递归函数,求斐波那契数列的第N项,并调用此函数求这个数列前N项的和

地址传递与递归如何同时使用


#include <iostream>
using namespace std;

void Fibonacci(long long *x, int n)
{
    if (n == 1 || n == 2)
    {
        *x = 1;
        return;
    }
    long long a, b;
    Fibonacci(&a, n - 1);
    Fibonacci(&b, n - 2);
    *x = a + b;
}
int main()
{
    long long a, sum = 0;
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        a = 0;
        Fibonacci(&a, i);
        // cout << a << " ";
        sum += a;
    }
    // cout << endl;
    cout << sum;
    return 0;
}

如下是一个详细代码实现,地址传递和递归同时使用了,望采纳

#include <iostream>

// Function prototype
int fibonacci(int& n);

int main()
{
    // 计算第N项
    int n = 10; // Assume N = 10 for this example
    int NthTerm = fibonacci(n);

    // 计算前N项和
    int sum = 0;
    for (int i = 1; i <= n; i++)
    {
        sum += fibonacci(i);
    }

    // 输出结果
    std::cout << "The Nth term of the Fibonacci sequence is: " << NthTerm << std::endl;
    std::cout << "The sum of the first N terms of the sequence is: " << sum << std::endl;

    return 0;
}

// 斐波那契数列函数定义
int fibonacci(int& n)
{
    if (n == 0 || n == 1)
    {
        return n;
    }

    return fibonacci(n-1) + fibonacci(n-2);
}