3

我使用 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整数溢出的可能性较小的倍数?如果我必须提取分子和分母(两种 Rusti64类型)并直接对它们进行数学运算,那很好。

4

0 回答 0