C++中的斐波那西算法 - 递归
Fibonacii's algorithm in C++ - recursively
我的代码有问题。有一个斐波那契的功能,我希望您知道做什么。还有两个文件: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;
如果要列出序列(如您的问题和代码所暗示)。
相关文章:
- 到连接组件算法的问题(递归)
- 需要为 C++ 中的以下问题设计递归算法
- 这种用于查找连续子数组中最大和的递归算法有什么优势吗?
- 给出不精确答案的递归Karatsuba算法
- 运行合并排序递归算法时EXC_BAD_ACCESS错误
- 如何改进搜索二项式系数的递归算法
- 如何转换多次调用自己的递归算法?
- 如何从算法中找到递归关系
- 递归合并排序算法实现
- 如何将字符串保存在最长的常见子序列递归算法中
- 这是河内算法的递归塔是一种不知情的搜索
- 编写递归算法以从链表中删除元素.编写递归算法以将元素添加到链表中
- 了解一种神秘地起作用的递归二进制搜索算法
- 指针似乎迷失在递归算法中
- 为什么我的递归快速排序算法有如此不平衡的分区
- 为什么这种递归子集和算法会导致指针分配错误
- 如何从递归算法返回节点
- C++中的斐波那西算法 - 递归
- 最长公共子序列算法递归解的记忆
- 快速排序算法(递归)