Reputation: 23
It should print the Fibonacci series up until a position, but it just prints 1 1 2, even if I ask for more than the first three elements. How can I fix this?
#include <iostream>
using std::cout;
using std::cin;
int main()
{
cout << "Enter a number: ";
int number;
cin >> number;
int count = 1;
int a = 1; //The first number of the Fibonacci's serie is 1
int b = 1; //The second number of the Fibonacci's serie is 2
while (count <= number)
{
if (count < 3)
cout << "1 ";
else
{
number = a + b; //Every number is the sum of the previous two
cout << number << " ";
if (count % 2 == 1)
a = number;
else
b = number;
}
count++;
}
return 0;
}
Upvotes: 1
Views: 92
Reputation: 1
You can try this code:
int main()
{
int n, t1 = 0, t2 = 1, nextTerm = 0;
cout << "Enter the number of terms: ";
cin >> n;
cout << "Fibonacci Series: ";
for (int i = 1; i <= n; ++i)
{
// Prints the first two terms.
if(i == 1)
{
cout << " " << t1;
continue;
}
if(i == 2)
{
cout << t2 << " ";
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
cout << nextTerm << " ";
}
return 0;
}
Upvotes: -2
Reputation: 403
It is like swapping the variable's values. You're using the number as limitation but in the loop you're using the same variable that is creating a logical error. Do the following changes and you're done (Y).
int main()
{
cout << "Enter a number: ";
int number;
cin >> number;
int count = 1;
int a = 1; //The first number of the Fibonacci's serie is 1
int b = 1;
int i = 1; //The second number of the Fibonacci's serie is 2
while (i <= number)
{
if (i < 3)
cout << "1 ";
else
{
count = a + b; //Every number is the sum of the previous two
a = b;
b = count;
cout << count << " ";
}
i++;
}
return 0;
}
Upvotes: 1
Reputation: 405715
You're using number
as the maximum number of loop iterations here:
while (count <= number)
But then inside the loop you're using the same variable as the current Fib value to output for each iteration.
number = a + b; //Every number is the sum of the previous two
cout << number << " ";
That's causing the loop to terminate prematurely. You need to pick different variable names for these two different values.
Upvotes: 2