日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

rust(10)-函数指针

發(fā)布時間:2025/3/12 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 rust(10)-函数指针 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
PS F:\learn\rustlearn> rustc learn1.rs PS F:\learn\rustlearn> .\learn1.exe 0.6823278038280194 PS F:\learn\rustlearn>

函數(shù)是一等公民,函數(shù)可作為函數(shù)的參數(shù)和返回值使用。
如下面代碼段所示

pub fn f_compute(com_fn:fn(f64)->f64,x:f64)->f64{com_fn(x) }

完整代碼如下:

use std::f64; pub fn get_next_x(x0:f64,x1:f64)->f64{let res1=&f_compute(fn1,x1);let res0=&f_compute(fn1,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 }fn main() {let tol=1e-8_f64;let x0=0.0_f64;let x1=4.0_f64;let mut x_i:f64=x1;let mut x_isub1:f64=x0;let mut x_iplus1:f64;let mut ans:f64=0.0_f64; let mut finished=false;for _n in 1..200 {x_iplus1=get_next_x(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!("{}",ans); } } 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 }fn main() {let tol=1e-8_f64;let x0=0.0_f64;let x1=4.0_f64;let mut x_i:f64=x1;let mut x_isub1:f64=x0;let mut x_iplus1:f64;let mut ans:f64=0.0_f64; let mut finished=false;for _n in 1..500 {x_iplus1=get_next_x(fn1,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!("{}",ans); }x_i=x1;x_isub1=x0;ans=0.0_f64; finished=false;for _n in 1..200 {x_iplus1=get_next_x(fn2,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!("{}",ans); } } PS F:\learn\rustlearn> rustc learn1.rs PS F:\learn\rustlearn> .\learn1.exe 0.6823278038280194 2.2514454804098265 PS F:\learn\rustlearn>

總結

以上是生活随笔為你收集整理的rust(10)-函数指针的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。