与溢出相乘:Rust运行时错误

k4ymrczo  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(150)

在Rust程序中,我试图写我需要乘以2 u64,并计算1的个数,当乘积表示为二进制时。

// Intentionally left uninitialized
let some_u64: u64;
let another_u64: u64;
let product = some_u64 * another_u64;

此操作将为product变量生成此“数据类型”-(我不确定它到底是什么)。

<u64 as Mul<u64>>::Output

当编译这个函数时,它不会返回任何错误。但是,当运行它时,它会返回以下错误。

thread 'main' panicked at 'attempt to multiply with overflow', src/file.rs:67:23
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

使用RUST_BACKTRACE=1环境变量

thread 'main' panicked at 'attempt to multiply with overflow', src/magics.rs:67:23
stack backtrace:
   0: rust_begin_unwind
             at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/std/src/panicking.rs:575:5
   1: core::panicking::panic_fmt
             at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/core/src/panicking.rs:65:14
   2: core::panicking::panic
             at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/core/src/panicking.rs:115:5
   3: rust_chess::magics::find_magics
             at ./src/file.rs:67:23
   4: rust_chess::magics::init
             at ./src/file.rs:10:13
   5: rust_chess::main
             at ./src/main.rs:11:5
   6: core::ops::function::FnOnce::call_once
             at /rustc/69f9c33d71c871fc16ac445211281c6e7a340943/library/core/src/ops/function.rs:251:5
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

我应该怎么做才能使2 u64相乘并在使用乘积时不出现运行时错误?
仅供参考,我曾尝试将其强制转换为u128,但不幸的是导致了相同的结果。

**编辑:**这里有一个playground link,可以看到一个可重复性最小的示例。

qq24tv8q

qq24tv8q1#

您可以先将u64 s转换为u128 s *,然后再将它们相乘以避免溢出:

let some_num: u64 = 36670911850479872;
let another_num: u64 = 18049651735527936;

let product = u128::from(some_num) * u128::from(another_num);

println!("{} * {} = {}", some_num, another_num, product);
36670911850479872 * 18049651735527936 = 661897187725405976746072861704192

相关问题