我使用num-rational crate的Rational64
类型将数字表示为带符号的64位整数的比率。我试图将一个数字向下舍入到另一个数字的下一个数字,当我以两种显而易见的方式中的任何一种方式执行时,我都会遇到整数溢出问题。请注意,这两个数字可能都是分数。
extern crate num_rational;
extern crate num_traits;
use num_rational::Rational64;
use num_traits::identities::Zero;
fn round(mut n: Rational64, increment: Rational64) -> Rational64 {
let rem = n % increment;
if !rem.is_zero() {
// normalize to a multiple of the increment, round down
// to the next integer, and then undo the normalization
n = (n * increment.recip()).trunc() * increment;
}
n
}
fn main() {
let a = Rational64::new(10_000_676_909_441, 8_872_044_800_000_000);
let b = Rational64::new(1, 1_000_000);
let c = round(a, b);
println!("{}", c);
}
extern crate num_rational;
extern crate num_traits;
use num_rational::Rational64;
use num_traits::identities::Zero;
fn round(mut n: Rational64, increment: Rational64) -> Rational64 {
let rem = n % increment;
if !rem.is_zero() {
n -= rem;
}
n
}
fn main() {
let a = Rational64::new(10_000_676_909_441, 8_872_044_800_000_000);
let b = Rational64::new(1, 1_000_000);
let c = round(a, b);
println!("{}", c);
}
有没有办法让n
向下舍入到increment
的倍数,这样整数溢出的可能性就会降低?如果我必须提取分子和分母(两个Rust i64
类型)并直接对它们进行数学运算,那就没问题。