Reputation: 3
I'm still very new to C++ still and decided to make a fibonacci sequence. It worked (Woo!) but it doesn't work as well as I would like it to.
what I mean by that is say for example I told my program to count the first 10 terms of the sequence I will get
"0, 1, 1" and then I have to press enter for each additional number until it hits ten in which case the program returns 0 and ends.
How do I get the program to display all the numbers I want to without hitting enter for each additional one?
Here is my script:
#include <iostream>
using namespace std;
int main()
{
int FibNum;
cout << "How many numbers of the Fibonacci Sequence would you like to see? \n\n";
cin>> FibNum;
cin.ignore();
int a = 0;
int b = 1;
int c = 2;
cout << "Fibonacci Sequence up to " << FibNum << " terms.\n\n";
cout << a << "\n" << b << "\n";
for (int c = 2; c < FibNum; c++) {
int d = a + b;
cout << d;
cin.ignore();
a = b;
b = d;
}
}
Thanks in advance for any help!
P.s. Also if you notice anything terrible I'm doing please feel free to correct me, I'm very aware I'm probably doing a lot wrong, I'm just trying to learn. :]
Upvotes: 0
Views: 262
Reputation: 93
Besides the previous answers,
To better format the output, add white space by changing this
cout << d;
to
cout << d << " ";
You may want to change the type of a
, b
and d
from int
to double
to prevent overflow.
(If you let FibNum=100
in your code, you should be able to observe overflow, meaning that you are going to get some incorrect numbers toward the end of the sequence.)
Upvotes: 2
Reputation: 234815
A few things:
1) Remove int c = 2;
as you're re-defining c
inside the for
loop.
2) Drop the line cin.ignore();
: in your for
loop: that will fix your "enter" problem; that line waits for some input then ignores it.
3) Put some white space in your output: e.g. cout << d << ' '
so your numbers are separated.
4) [Acknowledge vincent_zhang] Consider moving to uint64_t
as your data type for a
, b
, and d
. This is a standard type in C++11. It's a 64 bit unsigned integer type; adequate for a large number of terms.
and a small thing, bordering on personal opinion,
5) Use ++c
instead of c++
as the former will never run slower as, conceptually at least, post-increment has to take a copy of the original value.
Upvotes: 5
Reputation: 1181
Move cin.ignore() out of the loop then you dont need to enter to print all the 10 numbers of Fibonacci series
Upvotes: 1