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

问题描述

在上播放,并希望以相反的方式打印出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?

解决方案

您的代码不起作用,因为 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。


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?

解决方案

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在循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 14:09