I have a problem with my code. There is a Fibonacci’s function which I hope you know what does. And there two files: In0201.txt and Out0201.txt. As well, the programme should get the value from file “In0201.txt” and write the results to Out0201.txt.
Some value is being written but instead writing sequence of numbers ( to file ), it writes a value like it was a sum of all this numbers from sequence. Does anybody know why it happens ?
#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;
}
This code will output to the file a single integer number followed by a comma. If you want to output each of the return values from
fib(int n)then you’ll need to restructure your code so that the string you wish to write to file is appended inside the recursive loop.Solution
The purpose of
dummyStringis to disregard half of the results since they are being duplicated by calling fib twice.