斐波那契数列

本文介绍了一个Java程序,该程序能够生成指定长度的斐波那契数列。通过一个名为Fibonacci的类中的静态方法f实现,输入一个整数参数,输出从数列起始位置开始的相应数量的斐波那契数。
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);
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值