C++中的斐波那西算法 - 递归

Fibonacii's algorithm in C++ - recursively

本文关键字:算法 递归 C++      更新时间:2023-10-16

我的代码有问题。有一个斐波那契的功能,我希望您知道做什么。还有两个文件:in0201.txt和out0201.txt。同样,该程序应从文件" in0201.txt"中获取值,并将结果写入out0201.txt。

正在写一些值,而是编写数字序列(要文件),它写入一个值,就像从序列中的所有数字的总和一样。有人知道为什么会发生吗?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//Fibonacci
long double fib(int n) {
    if(n == 0)
    {
        return 0;
    }
    if(n == 1)
    {
        return 1;
    }
    return fib(n-1) + fib(n-2);
}
int main()
{
    int a;
    int tmp;
    ifstream inputFile("In0201.txt");
    if (inputFile.is_open()) {
        inputFile >> a;
        cout << "Loaded the value 'n' from file: " << endl;
        cout << a << " " << endl;
        inputFile.close();
    }
    ofstream outputFile("Out0201.txt");
    if (outputFile.is_open()) {
        tmp = fib(a);
        cout << "Fibonacci's sequence number: " << tmp << endl;
        outputFile << tmp << ", ";
        outputFile.close();
    }
    return 0;
}
if (outputFile.is_open()) {
    tmp = fib(a);
    cout << "Fibonacci's sequence number: " << tmp << endl;
    outputFile << tmp << ", ";
    outputFile.close();
}

此代码将输出单个整数号,然后是逗号。如果要从fib(int n)输出每个返回值,则需要重组代码,以便要写入文件的字符串在递归循环中附加。

解决方案

 long double fib(int n, ofstream &openFile) {
     if(n == 0)
     {
         return 0;
     }
     if(n == 1)
     {
         openFile<<1<<", ";
         return 1;
     }
     ofstream dummyStream;
     long double nextFib = fib(n-1, openFile) + fib(n-2, dummyStream);
     openFile<< nextFib <<", ";
     return nextFib;
 }

int main()
{
    int a;
    ifstream inputFile("In0201.txt");
    if (inputFile.is_open()) {
        inputFile >> a;
        cout << "Loaded the value 'n' from file: " << endl;
        cout << a << " " << endl;
        inputFile.close();
    }
    ofstream outputFile("Out0201.txt");
    if (outputFile.is_open()) {
        outputFile << 0 << ", ";
        fib(a, outputFile);
        outputFile.close();
    }
    return 0;
}

dummyString的目的是忽略结果的一半,因为它们通过两次致电FIB重复。

,因为您正在使用递归函数。它将斐波那契的总和从in0201.txt

计算到您的数字

您应该像这样更改功能:

long double fib(int n, ofstream openFile) {
 if(n == 0)
 {
     openFile<<0<<", ";
     return 0;
 }
 if(n == 1)
 {
     openFile<<1<<", ";
     return 1;
 }
 openFile<< fib(n-1) + fib(n-2)<<", ";
 return fib(n-1) + fib(n-2);
}

还没有品尝过它,但这是这个主意。

考虑将行outputFile << tmp << ", ";更改为

for(int i = 0; i < a; i++)
    outputFile << fib(i) << ", ";
outputFile << fib(a) << endl;

如果要列出序列(如您的问题和代码所暗示)。