[ 3 / biz / cgl / ck / diy / fa / ic / jp / lit / sci / vr / vt ] [ index / top / reports ] [ become a patron ] [ status ]
2023-11: Warosu is now out of extended maintenance.

/sci/ - Science & Math


View post   

File: 36 KB, 802x497, Fibonacci.png [View same] [iqdb] [saucenao] [google]
3286264 No.3286264 [Reply] [Original]

Hey, /sci/. I'm working on learning Java right now and I'm trying to make a Fibonacci sequence generator. What am I doing wrong?

class fibonacci{
public static void main(String args[]) {
int num1 = 0;
int num2 = 1;
int num3 = num1 + num2;
int n = 0;
while(n < 10){
System.out.println(num3);
num1 = num2;
num2 = num3;
n++;
}
}
}

All I get is a bunch of 1s. I just started learning today, so be nice, please.

>> No.3286280

Why would the value of num3 change? That's what you're outputting.

>> No.3286288

>>3286280
So would I throw another
num3 = num1 + num2;
inside of the while?

>> No.3286296

>>3286288
Yup... I knew it was something obvious. Thanks, anon. :)

>> No.3286299

>>3286288

Yes, but where you put it is important.

>> No.3286310

>>3286288

num3 = num1 + num2 needs to be inside your loop

The way you have it now, your loop isn't doing anything. There are also more efficient ways to generate Fibonacci numbers, but stick to the simplest for now.