c++ - Can't print Fibonacci series -
i writing little snippet fibonacci number sequence depending on user input. if user supplies 4 input, should homecoming him first n members of fibonacci sequence.
#include <iostream> using namespace std; int main (){ int = 0; int b = 1; int c; int n = 3; n -= 2; if (n == 1){ cout << << endl; } else { cout << << b << endl; (int i=0;i<n;i++){ c = b + a; cout << c << endl; = b; b = c; } } }
however, end getting 0 output whatever number supply. have working in php , kinda miss i've blundered. guess don't render input , output properly.
int =0; int n = 3; n -= 2; if (n == 1){ cout << << endl; }
you have n
equal 3, subtract 2, n
equal 1, so, come in if body , output a
, zero.
[edit]
you don't seem input -as stated in comment- in programme (you utilize std::cin
or std::getline()
this), mean have input hard-coded, changing value of n
hand.
you may want check how fibonacci series programme expected work:
fib. @ rosseta page. fib. recursion non-recursive fib.after reading links provided above, should able see code should changed this:
#include <iostream> using namespace std; int main (){ int = 1; int b = 0; int c; int n = 10; // "input" 10 if (n == 0 || n == 1) { // 0 , 1 case cout << n << endl; } else { (int = 2; <= n; ++i) { // here want reach n c = + b; b = a; = c; } cout << c << endl; } homecoming 0; }
however, code above outputs result. should modify terms of sequence, i'll leave have fun too.
in order allow user input number, change:
int n = 10;
to
int n; std::cout << "please, input.\n"; std::cin >> n;
however, letting user inputting must followed validation of input. see users can, accident or not, provide input in program, can cause undefined behaviour.
c++ fibonacci
No comments:
Post a Comment