gpt4 book ai didi

for-loop - 如何使循环反向排序?

转载 作者:行者123 更新时间:2023-11-29 08:20:57 24 4
gpt4 key购买 nike

Editor's note: This question was asked before Rust 1.0 was released and the .. "range" operator was introduced. The question's code no longer represents the current style, but some answers below uses code that will work in Rust 1.0 and onwards.

我在玩Rust by Example website并想反向打印出 fizzbuzz。这是我尝试过的:

fn main() {
// `n` will take the values: 1, 2, ..., 100 in each iteration
for n in std::iter::range_step(100u, 0, -1) {
if n % 15 == 0 {
println!("fizzbuzz");
} else if n % 3 == 0 {
println!("fizz");
} else if n % 5 == 0 {
println!("buzz");
} else {
println!("{}", n);
}
}
}

没有编译错误,但没有打印出任何东西。如何从 100 迭代到 1?

最佳答案

正向循环是这样的:

for x in 0..100 {
println!("{}", x);
}

并通过调用 Iterator::rev 完成反向循环颠倒顺序:

for x in (0..100).rev() {
println!("{}", x);
}

关于for-loop - 如何使循环反向排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47275339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com