Reputation: 7
I'm trying to print Fibonacci series in an file named "fibonacci.txt" up to 200 terms But after execution the file contained some wrong sums,
some sums were less than expected
I'm attaching the code and output with question.
int main(){
ofstream text_file;
text_file.open("fibonnacci.txt");
unsigned long sum, sum1=1, sum2=1;
text_file<<sum1<<"\t"<<sum2<<"\t";
for(int i = 1; i < 200; i++) {
sum = sum1 + sum2;
text_file<<sum<<"\n";
/*if(i%5 == 0){
text_file<<"\n";
}*/
sum2 = sum1;
sum1 = sum;
}
text_file<<"\n";
return 0;
}
OUTPUT
102334155
165580141
267914296
433494437
701408733
1134903170
1836311903
2971215073
512559680
3483774753
3996334433
3185141890
2886509027
1776683621
368225352
2144908973
2513134325
363076002
2876210327
3239286329
1820529360
764848393
2585377753
3350226146
These are some mid terms. Clearly we can see that some terms are less than the previous terms by calculating number of digits.
Upvotes: 0
Views: 178
Reputation: 697
You have a overrun in your sum variable. unsigned long has a maximum number of 4294967295. Try usings __int64 for example
Upvotes: 2