更新 6.flow_and_control 流程控制
This commit is contained in:
parent
6509f62182
commit
752dfce9a8
@ -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<i32> = 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);
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user