rust(11)-函数作为返回值和match(类似于switch)
生活随笔
收集整理的這篇文章主要介紹了
rust(11)-函数作为返回值和match(类似于switch)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
繼續(xù)以解一元多次方程割線法為例
PS F:\learn\rustlearn> rustc learn2.rs PS F:\learn\rustlearn> .\learn2.exe function0,解:0.6823278038280194 function1,解:2.2514454804098265 function2,解:0.024960915745356877 function3,解:0.024960915745356877 function4,解:0.024960915745356877 function5,解:0.006247558631002903 PS F:\learn\rustlearn> use std::f64; pub fn get_next_x(com_fn:fn(f64)->f64,x0:f64,x1:f64)->f64{let res1=&f_compute(com_fn,x1);let res0=&f_compute(com_fn,x0);x1-res1*((x1-x0)/(res1-res0)) } pub fn f_compute(com_fn:fn(f64)->f64,x:f64)->f64{com_fn(x) }pub fn fn1(x:f64)->f64{x.powi(3)+x-1.0_f64 } pub fn fn2(x:f64)->f64{2.98*x.powi(3)-5.21*x.powi(2)-7.6_f64 } pub fn fn3(x:f64)->f64{x.powi(4)+x.powi(3)-1.0_f64 } pub fn fn4(x:f64)->f64{x.powi(5)+x.powi(4)-1.0_f64 } pub fn get_fn(i:i32)->fn(f64)->f64 {match i{0=>fn1,1=>fn2,2...4=>fn3,_=>fn4,} }fn main() {let tol=1e-8_f64;let x0=0.0_f64;let x1=4.0_f64;let mut x_i:f64;let mut x_isub1:f64;let mut x_iplus1:f64;let mut ans:f64; let mut finished;let mut fn_comp;for i in 0..6{fn_comp=get_fn(i);x_i=x1;x_isub1=x0;ans=0.0_f64; finished=false; for _n in 1..500 {x_iplus1=get_next_x(fn_comp,x_isub1,x_i);if (x_iplus1-x_i).abs()<tol { ans=x_iplus1;finished=true;break;} x_isub1=x_i;x_i=x_iplus1;}if finished{println!("function{},解:{}",i,ans); }else{println!("function{},找不到解",i); } } }1、get_fn接收一個參數(shù)i,返回一個函數(shù)(fn1-fn4)。
2、 match函數(shù)相當(dāng)于c++的switch,通過i判斷指定調(diào)用哪個函數(shù)(fn1-fn4) ,
總結(jié)
以上是生活随笔為你收集整理的rust(11)-函数作为返回值和match(类似于switch)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java代理设计模式(Proxy)的具体
- 下一篇: Java字符串池(String Pool