You should check the new element for being to big, not the last found element for being smaller.
I won't go into more detail, because you said it's homework and probably don't need more.
Loop termination in C fibonacci implementation
Question
My task is to find fibonacci series elements not larger than given in input. The problem is that I get one extra result (larger then number from input).
for example: when I enter 15 as a max, I get 1,1,2,3,5,8,13,21 which is incorrect.
My code:
#include <stdio.h>
int main()
{
int n, first = 0, second = 1, next =0, c;
printf("Enter max value\n");
scanf("%d",&n);
printf("Values smaller than %d :-\n",n);
for ( c = 1 ; n>=next; c++)
{
if ( c <= 1 )
next = c;
else
{
next = first + second;
first = second;
second = next;
}
printf("%d\n",next);
}
return 0;
}
Any ideas?
Solution
OTHER TIPS
If you get values higher than your max it's because you do this test first:
n>=next
(inside the for)
THEN
next = first + second;
Which mean next>=n
for the last iteration will be true.
You shoud change the limit test or when the results are printed (eg before next = first + second;
)
The problem is with your last loop. Work with a debugger if you need; or you can just go step by step in your mind. In your case, when next == 13
, first == 5
and second == 8
. then first
becomes 8, and second
becomes 13. However, at this moment next
is still 13, so when it goes back the loop, n >= next
still returns true
, and it will go on one more loop, thus one more output than you expected. I won't tell you how to change it, cuz as others said, it's homework. I just want to show you how to find the problem.