如题所示,代码如下:
#[derive(Debug,Clone)]
struct Fib{
item:Vec<u128>,//综合对比,u128类型能正常显示数列中的第185位并求和
}
impl Fib{
fn new(mut self,i:u128)->Self{
match i{
1..=1 =>{
self.item.push(0);
},
2.. =>{
self.item.push(0);
self.item.push(1);
for e in 2..i{
self.item.push(self.item[(e-1) as usize]+self.item[(e-2) as usize]);
}
},
_ => {println!("该斐波那契数列无效…")}
}
self
}
fn totalnum(self)->u128{
let t = self.item.iter().fold(0,|sum,e|sum+e);
t
}
}
fn main(){
let newfib = Fib{
item:Vec::new()
};
let fib = newfib.new(7);//此处最大能填到185
println!("斐波那契数列各项值为:{:?}",fib);
println!("斐波那契数列各项之和:{}",fib.totalnum());
}
/*
斐波那契数列各项值为:Fib { item: [0, 1, 1, 2, 3, 5, 8] }
斐波那契数列各项之和:20
---------------------------------------------------
该斐波那契数列无效…
斐波那契数列各项值为:Fib { item: [] }
斐波那契数列各项之和:0
*/