object ImplicitFunc { //类
def main(args: Array[String]): Unit = { //main方法
import scala.collection.mutable.ArrayBuffer //ArrayBuffer包使数组可变
def dg(n: Int): Array[Int] = { //类型为Int
def func(n: Int): Int = { //定义方法
if (n<=2) 1 else func(n - 1) + func(n - 2) //特征<=2,输出均为1,>2为(n-1)+(n-2)
}
println(func(1)) //检查特例值数据
val buffer = new ArrayBuffer[Int] //new一个对象
for (i <- 1 to n) { //确定i的取值范围
buffer.append(func(i)) //往buffer里添加func产生的数据
}
buffer.toArray //toArray
}
dg(9).foreach(x => print(s"$x,")) //遍历输出
}
}
1 //输出结果
1,1,2,3,5,8,13,21,34,
scala递归实现斐波那契数列1,1,2,3,5,8,13,21
最新推荐文章于 2023-02-11 08:36:37 发布