【发布时间】:2023-01-21 15:34:28
【问题描述】:
我正在尝试制作一个程序,使用 rand 来显示猜门的成功率(就像在电视节目中一样)。它编译但不运行。
use rand::Rng;
fn main() {
let mut right_answers = 0;
for _ in 0..100 {
let mut not_already_chosen: Vec<usize> = vec![1, 2, 3];
let mut rng = rand::thread_rng();
let right_door = rng.gen_range(1..4);
let mut guest_choose: usize = rng.gen_range(1..4);
not_already_chosen.remove(guest_choose);
let presenter_choose = not_already_chosen[rng.gen_range(0..3)];
not_already_chosen.remove(presenter_choose);
guest_choose = not_already_chosen[0];
if guest_choose == right_door {
right_answers += 1;
}
}
println!("Rate: {}", (right_answers / 100));
}
当我使用 cargo run 时,它返回:
Compiling choose_the_door v0.1.0 (.../choose_the_door)
Finished dev [unoptimized + debuginfo] target(s) in 0.47s
Running `target/debug/choose_the_door`
thread 'main' panicked at 'removal index (is 2) should be < len (is 2)', src/main.rs:16:28
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
我试图删除部分代码以查看问题所在。当我删除具有“not_already_chosen.remove(...);”的行时它可以运行,但代码一开始并没有按照我的意愿进行。我做错了什么?
【问题讨论】:
标签: rust rust-cargo