Write a program that generates the first 100 Fibonacci numbers. This is what is
ID: 3560344 • Letter: W
Question
Write a program that generates the first 100 Fibonacci numbers.
This is what is have so far:
//Generate the list of the first 100 Fibonacci numbers
#include<stdio.h>
#include<conio.h>
int main()
{
int n, first = 0, second = 1, next, c;
printf("How many terms of the Fibonacci series would you like to know? ");
scanf("%d",&n);
printf("First %d terms of Fibonacci series are : ",n);
for ( c = 0 ; c < n ; c++ )
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d ",next);
}
getch();
return 0;
}
Now the problem is that once is gets to the 46th number in the series it starts going all weird, with - numbers. I have tried using long and longlong int but with no avail. can anyone point out where im going wrong.
Explanation / Answer
The problem with your code is once number gets higher the size of int in c++ and depending upon your architecture is 16 bits hence it can store values from -32768 and 32767 while your 46th number in fiboacci series is pretty large in order to store up to 100 numbers of fibonacci you will be needing use data type long long int which is of size 64 bits hence values range is much higher.
hope this helps
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.