如何做一个反向排序的Rust在循环? [英] How to make a reverse ordered for loop in Rust?

查看:508
本文介绍了如何做一个反向排序的Rust在循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


编者按:这个问题在Rust 1.0发布之前就已经问过了,引入了 .. range运算符。这个问题的代码不再代表当前的风格,但下面的一些答案使用的代码,将在Rust 1.0及以后的版本。


Rust by Example网站上播放,并希望以相反的方式打印出fizzbuzz。这是我试过的:

  fn main(){
//`n`将取值为1 ,2,...,100每次迭代
for 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?

解决方案


编者按:铁锈1.0之前的铁锈。

您的代码不起作用,因为 uint 值-1的code>等于uint的最大值。 range_step迭代器在检测到溢出时立即停止。使用一个int修复了这个问题。

$ p $ st $ :: $ c $ std :: iter :: range_step(100i,0,-1)

您也可以使用 rev()来反转迭代器。 (0u,100).rev(){...}
>



虽然请注意这将从99-> 0,而不是100-> 1。


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.

I was playing on the Rust by Example website and wanted to print out fizzbuzz in reverse. Here is what I tried:

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);
        }
    }
}

There were no compilation errors, but it did not print out anything. How do I iterate from 100 to 1?

解决方案

Editor's note: This question refers to parts of Rust that predate Rust 1.0. Look at other answers for up to date code.

Your code doesn't work because a uint of value -1 is equal the maximum value of uint. The range_step iterator stops immediately upon detecting overflow. Using an int fixes this.

std::iter::range_step(100i, 0, -1)

You can also reverse an iterator with rev().

for n in range(0u, 100).rev() { ... }

Though note that this will be from 99->0, rather than 100->1.

这篇关于如何做一个反向排序的Rust在循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆