Fibonacci fcn using vector, wont print in main

I created a Fibonacci function but am having trouble printing out the result in main.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
using namespace std;
  vector<int> fib(int n)  //# return Fibonacci series up to n
//"""Return a list containing the Fibonacci series up to n."""
{
	vector <int> result;
	int a, b;
	a=0;
	b=1;

	while (a < n)
	{
		result.push_back(a);    
		n = a + b;
		a = b;
		b = n;
	}
	return result;
}
int main()
{ 
   int n2,z;
   n2 = 400000;
   z = fib(n2);
   cout << z << endl;

}


I get the following error when running the code: '=': cannot convert from 'std::vector<int,std::allocator<_Ty>>' to 'int'

Last edited on
Trying to assign a std::vector to an int won't work.

Your Fibonacci algorithm is a bit flawed, you only retrieve one value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <vector>
#include <string>

std::vector<int> fib(int limit)
{
   std::vector<int> result;

   int fib1 { };
   int fib2 { 1 };

   int next_fib { fib1 + fib2 };

   while (next_fib <= limit)
   {
      result.push_back(fib1);

      fib1 = fib2;
      fib2 = next_fib;

      next_fib = fib1 + fib2;
   }

   return result;
}

int main()
{
   int fib_num { 40000 };

   std::vector<int> fib_vec { fib(fib_num) };

   std::cout << "The size of the Fibonacci Series with " << fib_num
             << " terms is " << fib_vec.size() << "\n\n";

   for (const auto& itr : fib_vec)
   {
      std::cout << itr << ' ';
   }
   std::cout << '\n';
}

The size of the Fibonacci Series with 40000 terms is 22

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946
Got it to work, thanks!
Topic archived. No new replies allowed.