I have written a program in c++ to output the number in the fibonacci sequence you tell it to. It works up until about the 47th number, after that it prints out completely different numbers, even negatives, and none of them have more than 9 or 10 individual integers. Here is the code
#include <iostream>
int a = 0;
int b = 1;
int c;
int var = 0;
int num;
void fibonacci()
{
using namespace std;
c = a;
a = a + b;
b = c;
var += 1;
}
void loop()
{
using namespace std;
for (int iii=0; iii<num; iii++)
fibonacci();
}
int main()
{
using namespace std;
cout << "What fibonacci number do you want to know? ";
cin >> num;
cin.get();
loop();
cout << "" << endl;
cout << c << endl;
cin.get();
a = 0;
b = 1;
var = 0;
return main();
}
Is there some sort of limit on how many characters c++ can print at once?
Increase your data type size/capacity from an
intto anunsigned longorunsigned long long. Each of these has a size which, when exceeded, creates a bit pattern which will create an almost certainly incorrect value. Also, since your number can never be negative, allowing part of the number’s size to be used for negative values (which is a bit) wastes the maximum number you can represent.Also, you should add a check to detect this case. If a value ever goes down in this algorithm, you have clearly exceeded the limits of your data type. At this point, print a polite error that you cannot calculate the number because it is too large.