随机求斐波拉契数列第n位的代码
Posted Daemondz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了随机求斐波拉契数列第n位的代码相关的知识,希望对你有一定的参考价值。
1------------------------------------------------------------
package oo.day02;
import java.util.Scanner;
public class FibonacciSequence {
public static void main(String[] args) {
System.out.println("请输入斐波拉契数列第n项,n>0");
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int o=f(n);
System.out.println("斐波拉契数列第"+n+"项的值为:"+o);
int d1=f(45);
System.out.println(d1);
int d2=f(46);
System.out.println(d2);
double goldenCut=(double) d1/d2;
System.out.println(goldenCut);
}
private static int f(int n) {
int []arr=new int[n];
if(n==1){
arr[0]=1;
}else if(n==2){
arr[1]=1;
}else if(n>2){
arr[0]=1;
arr[1]=1;
for(int i=2;i<arr.length;i++){
arr[i]=arr[i-1]+arr[i-2];
}
}return arr[n-1];
}
}
2------------------------------------------------------------------------------
package oo.day02;
import java.util.Scanner;
public class FibonacciSequence2 {
public static void main(String[] args) {
System.out.println("请输入斐波拉契数列第n项,n>0");
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int o=f(n);
System.out.println("斐波拉契数列第"+n+"项的值为:"+o);
double goldenCut=(double)f(45)/f(46);
System.out.println(goldenCut);
}
private static int f(int n) {
int a=1,b=1,c=0;
if(n<=2){
c=1;
}else{
for(int i=1;i<=n-2;i++){
c=a+b;
a=b;
b=c;
}
}
return c;
}
}
3---------------------------------------------------------
package oo.day02;
import java.util.Scanner;
public class FibonacciSequence3 {
public static void main(String[] args) {
System.out.println("请输入斐波拉契数列第n项,n>0");
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int o=f(n);
System.out.println("斐波拉契数列第"+n+"项的值为:"+o);
double goldenCut=(double)f(45)/f(46);
System.out.println(goldenCut);
}
private static int f(int n) {
if(n==1||n==2){
return 1;
}else{
return f(n-1)+f(n-2);
}
}
}
以上是关于随机求斐波拉契数列第n位的代码的主要内容,如果未能解决你的问题,请参考以下文章