Skip to content

Latest commit

 

History

History
45 lines (31 loc) · 1.13 KB

rand-range.zh.md

File metadata and controls

45 lines (31 loc) · 1.13 KB

生成范围内的随机数

[![rand-badge]][rand] [![cat-science-badge]][cat-science]

Rng::gen_range,在半开放[0, 10)范围(不包括10)生成随机值。

extern crate rand;

use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();
    println!("Integer: {}", rng.gen_range(0, 10));
    println!("Float: {}", rng.gen_range(0.0, 10.0));
}

Uniform可以用来获得均匀分布的值。下面的代码是相同作用,但是当在相同范围内,重复生成数字时可能更快。

extern crate rand;


use rand::distributions::{Distribution, Uniform};

fn main() {
    let mut rng = rand::thread_rng();
    let die = Uniform::from(1..7);

    loop {
        let throw = die.sample(&mut rng);
        println!("Roll the die: {}", throw);
        if throw == 6 {
            break;
        }
    }
}