在Java中,我将如何找到第n个斐波纳契数字? [英] In java, how would I find the nth Fibonacci number?
问题描述
$ b $ pre $
int num = 0;
int num2 = 1;
int loop;
int fibonacci;
System.out.print(num2);
for(loop = 1; loop <= 10; loop ++)
{
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
System.out.print(+ fibonacci);
$ b 我的问题在于试图找出指定的 N 如果我想在序列中找到第6个元素,那么我将如何找到这个数字,在你的代码中, num
开始于0 th 斐波那契数,而 num1
作为1 st 。所以要找到n th ,你必须迭代 n
次:
<$ (循环= 0;循环< n;循环++)
{
fibonacci = num + num2; p $ p $
num = num2;
num2 = fibonacci;
}
System.out.print(num);
,只有在完成后才能打印。
当循环计数器 loop
的值为 k
, num
保存了第k个斐波那契数并且 num2
(k + 1) th 。
>
Determining the Fibonacci sequence is easy enough to figure out:
int num = 0;
int num2 = 1;
int loop;
int fibonacci;
System.out.print(num2);
for (loop = 1; loop <= 10; loop ++)
{
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
System.out.print(" " + fibonacci);
}
My problem lies with trying to pinpoint the value for a specified N. As in, If I want to find the 6th element in the sequence, which is 8, how would I find that number, and only that number?
解决方案 In your code, num
starts as the 0th Fibonacci number, and num1
as the 1st. So to find the nth, you have to iterate the step n
times:
for (loop = 0; loop < n; loop ++)
{
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
}
System.out.print(num);
and only print it when you've finished.
When the loop counter loop
has the value k
, num
holds the kth Fibonacci number and num2
the (k+1)th.
这篇关于在Java中,我将如何找到第n个斐波纳契数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!