如何在运行时确定下面代码(rust playground link)中1.0005
的精度为4?:
fn round(n: f64, precision: u32) -> f64 {
(n * 10_u32.pow(precision) as f64).round() / 10_i32.pow(precision) as f64
}
fn main() {
let x = 1.0005_f64;
println!("{:?}", round(x, 1));
println!("{:?}", round(x, 2));
println!("{:?}", round(x, 3));
println!("{:?}", round(x, 4));
println!("{:?}", round(x, 5));
}
最佳答案
我不确定我是否正确地理解了这个问题。你要小数位数吗?
fn round(n: f64, precision: u32) -> f64 {
(n * 10_u32.pow(precision) as f64).round() / 10_i32.pow(precision) as f64
}
fn precision(x: f64) -> Option<u32> {
for digits in 0..std::f64::DIGITS {
if round(x, digits) == x {
return Some(digits);
}
}
None
}
fn main() {
let x = 1.0005_f64;
println!("{:?}", precision(x));
}
Playground
我还建议将round函数中的类型放大一点,这样就不会很快遇到溢出。上面的代码已经失败了。
fn round(n: f64, precision: u32) -> f64 {
let precision = precision as f64;
(n * 10_f64.powf(precision)).round() / 10_f64.powf(precision)
}