fibonacci

Write your question here: why do I get negative numbers?


#include <iostream>

int main() {

int num, first_number=0,second_number=1,next_number;
std::cout<<"Enter how many terms you want to print:";
std::cin>>num;

std::cout<<"The Fibonacci series is:\n";


for(int i=0;i<num;i++) {

std::cout<<first_number<<"\n";

next_number = first_number + second_number;
first_number = second_number;
second_number = next_number;

}


}
Last edited on
Because int is finite.

Keep num at 47 or less ... or switch to unsigned long long for a few more.
Just to add a small note: As soon as your int values overflow, your program engenders undefined behavior. It just so happens that "overflow by wrapping around to negative integers" is the behavior that often occurs here.
https://en.cppreference.com/w/cpp/language/ub#Signed_overflow

Often, code will wrap back to negative when there isn't optimization enabled, but as soon as you enable optimization... the compiler has a field day.

1
2
3
int foo(int x) {
    return x+1 > x; // either true or UB due to signed overflow
}

may be compiled as:
1
2
3
int foo(int x) {
    return 1;
}
Last edited on
Topic archived. No new replies allowed.