import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i<count; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for(int i=0; i<count; i++)
{
System.out.print(fib[i] + " ");
}
}
}
这是我非常简单的Fib程序,我不知道为什么它总是阻止一个数字短。例如:
运行:请输入数字6 1 1 2 3 5 8建立成功(总时间:5 秒)
运行:请输入数字7 1 1 2 3 5 8 13建立成功(总计 时间:5秒)
我在FOR循环中认为它应该是“(int i = 2; i &lt; = count;”
但是当我在两者中放入大于或等于,或者在FOR循环中它给我一个错误
有什么建议吗?我知道它很容易让我忽视
答案 0 :(得分:1)
您的代码提供了正确的输出。但是如果你还需要一个元素,尝试使用count + 1初始化数组,然后让你的循环运行i&lt; = count
public static void main(String[] args) {
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count+1];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i <= count; i++){
fib[i] = fib[i-1] + fib[i-2];
}
for(int i=0; i <= count; i++){
System.out.print(fib[i] + " ");
}
}
}
答案 1 :(得分:1)
数组是从零开始的。这意味着,如果您有以下数组,那么(假设为count = 5
):
int[] fib = new int[5];
然后您可以访问fib[0]
,fib[1]
,fib[2]
,fib[3]
和fib[4]
。所以
for (int i = 0; i < 5; i++) {
System.out.print(fib[i] + " ");
}
没关系。因为它将访问fib
中的所有内容,从索引0开始,并使用小于5的最后一个索引停止,即4.如果您这样做:
for (int i = 0; i <= 5; i++) {
System.out.print(fib[i] + " ");
}
然后您将访问小于 OR EQUAL TO 5的最后一个索引,即5。但是,如前所述,fib[5]
无效。这就是给你错误的原因。
答案 2 :(得分:1)
更简单的解决方案是避免首先需要一个数组,而不需要正确的大小。
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner in = new Scanner(System.in);
int count = in.nextInt();
long a = 1, b = 1;
for(int i = 0; i < count; i++) {
System.out.print(a + " ");
long c = a + b;
a = b;
b = c;
}
System.out.println();
}
答案 3 :(得分:0)
int fib []应该还有一个数组元素空间,因此可以存储fib [count]。
import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count + 1];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i <= count; i++)
{
fib[i] = fib[i-1] + fib[i-2];
}
for(int i = 0; i<= count; i++)
{
System.out.print(fib[i] + " ");
}
}
}
答案 4 :(得分:0)
public class Fibonacci
{
private int [] fibArray;
public Fibonacci()
{
}
public void Fibonacci()
{
fibArray = new int[0];
}
public void setFibonnaci(int size)
{
fibArray = new int[size];
if(fibArray.length == 1)
{
fibArray [0] = 0;
}
else if(fibArray.length == 2)
{
fibArray[0] = 0;
fibArray[1] = 1;
fibArray[2] = 2;
}
else
{
fibArray[1] = 1;
fibArray[0] = 0;
for(int x = 2; x < fibArray.length; x++)
{
fibArray [x] = fibArray[x-1] + fibArray[x-2];
}
}
}
public int getSequence(int number)
{
if(number -1 < fibArray.length)
{
return fibArray[number - 1];
}
return -1;
}
//check the test case for getFibo
public String toString()
{
String output = "";
for (int x = 0; x < fibArray.length; x++)
{
output += x + " - " + fibArray[x];
}
return output;
}
}
迟到的反应,但新的网站,只是想帮助。这个纤维类100%