面试题答案
一键面试fn main() {
let f1 = 0.1;
let f2 = 0.2;
let result = f1 + f2;
println!("The result of addition: {}", result);
}
浮点数在计算机中以二进制形式存储,由于十进制小数(如0.1和0.2)无法精确表示为有限长度的二进制小数,会存在精度损失。所以0.1 + 0.2
的结果在计算机中并非精确的0.3
。
处理浮点数精度问题的方法:
- 使用指定精度类型:例如
f64
比f32
有更高精度,在可能的情况下优先选择f64
。 - 比较时使用误差范围:在比较两个浮点数时,不直接使用
==
,而是判断它们的差值是否在一个可接受的误差范围内,例如:
fn main() {
let f1 = 0.1;
let f2 = 0.2;
let result = f1 + f2;
let expected = 0.3;
let epsilon = 1e-9;
if (result - expected).abs() < epsilon {
println!("Results are approximately equal");
} else {
println!("Results are not approximately equal");
}
}
- 使用定点数:如果应用场景对精度要求非常高且小数范围有限,可以考虑使用定点数库,例如
rust_decimal
库,它可以精确表示小数。
use rust_decimal::Decimal;
fn main() {
let f1 = Decimal::from_str("0.1").unwrap();
let f2 = Decimal::from_str("0.2").unwrap();
let result = f1 + f2;
let expected = Decimal::from_str("0.3").unwrap();
if result == expected {
println!("Results are exactly equal");
}
}