public class fibonacci
{
public static void main(String[] args)
{
int a=0,b=1,c=2;
while(a<4000000)
{
a=b;
b=c;
c=a+b;
System.out.println(a);
}
}
}
Trying to print Fibonacci series less than 400000, but it is printing 5702887 as well.
Rearrange the printing and the checking, so that both act on the same value
int a=1,b=1,c=2;
while(a<4000000)
{
System.out.println(a);
a=b;
b=c;
c=a+b;
}
This outputs the fibonacci sequene, with two times "1" at the start.
If you want "1, 2, 3..." use
int a=1,b=2,c=3;
Fibonacci series start from 1. look at this . I gave solution for your code. You set a=b
after check a<4000000
. then you need to check with b.
int a=0,b=1,c=2;
while(b<4000000)
{
a=b;
b=c;
c=a+b;
System.out.println(a);
}
您的代码很好,您所需要做的就是在计算下一个数字之前放入打印语句, 因为3524578 <5702887
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.