From 752dfce9a87e5411640a460ad70a765ec36527dc Mon Sep 17 00:00:00 2001 From: shikong <919411476@qq.com> Date: Sun, 2 Jun 2024 21:15:43 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=206.flow=5Fand=5Fcontrol=20?= =?UTF-8?q?=E6=B5=81=E7=A8=8B=E6=8E=A7=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 6.flow_and_control/src/main.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/6.flow_and_control/src/main.rs b/6.flow_and_control/src/main.rs index 01786e7..993e6ee 100644 --- a/6.flow_and_control/src/main.rs +++ b/6.flow_and_control/src/main.rs @@ -31,4 +31,36 @@ fn main() { println!("当随机生成的数 >={} 且 <= {}时结束", min_num,max_num); println!("最终的随机数为: {}", num); + + println!("{}", "=".repeat(50)); + + // 使用 loop 实现 随机生成 5 次随机数并打印过程 + let mut counter = 0; + let mut vec:Vec = vec!(); + let result = loop { + counter += 1; + num = fn_rand_num(); + vec.push(num); + println!("随机数为: {}", num); + if counter == 5 { + // 可使用 break 退出循环并返回结果 + break num; + } + }; + println!("最终的随机数为: {}", result); + + println!("{}", "=".repeat(50)); + + // for 循环遍历 vec 并打印 + for num in &vec { + println!("vec 中的随机数为: {}", num); + } + + println!("{}", "=".repeat(50)); + + // 切片获取 vec 中最后两个元素 + let slice = &vec.as_slice()[vec.len()-2..vec.len()]; + for x in slice { + println!("slice 中的元素为: {}", x); + } }