The Question:
A Fibonacci sequence is the sequence of numbers 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on, where each number (from the third on) is the sum of the previous two. Create a method that takes an integer as an argument and displays that many Fibonacci numbers starting from the beginning, e.g., If you run java Fibonacci 5 (where Fibonacci is the name of the class) the output will be: 1, 1, 2, 3, 5.
My Answer:
public class Fibonacci {
/**
* @param args
*/
static void f(int i){
if (i < 2)
System.out.println("The number you entered must be bigger than 1");
else{
int a[] = new int[i];
for(int j = 0;j < i;j++) {
a[0] =a[1] = 1;
if(j >= 2){
a[j] = a[j-1] +a[j-2];
}
System.out.print(a[j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Fibonacci.f(9);
Fibonacci.f(7);
Fibonacci.f(4);
}
}
A Fibonacci sequence is the sequence of numbers 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on, where each number (from the third on) is the sum of the previous two. Create a method that takes an integer as an argument and displays that many Fibonacci numbers starting from the beginning, e.g., If you run java Fibonacci 5 (where Fibonacci is the name of the class) the output will be: 1, 1, 2, 3, 5.
My Answer:
public class Fibonacci {
/**
* @param args
*/
static void f(int i){
if (i < 2)
System.out.println("The number you entered must be bigger than 1");
else{
int a[] = new int[i];
for(int j = 0;j < i;j++) {
a[0] =a[1] = 1;
if(j >= 2){
a[j] = a[j-1] +a[j-2];
}
System.out.print(a[j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Fibonacci.f(9);
Fibonacci.f(7);
Fibonacci.f(4);
}
}
本文介绍了一个Java程序,该程序能够生成指定长度的斐波那契数列。通过一个名为Fibonacci的类中的静态方法f实现,输入一个整数参数,输出从数列起始位置开始的相应数量的斐波那契数。
8万+

被折叠的 条评论
为什么被折叠?



