Home »
Rust »
Rust Programs
Rust program to generate a floating-point random number between a specific range
Rust | Random Numbers Example: Write a program to generate a floating-point random number between a specific range.
Submitted by Nidhi, on November 12, 2021
Problem Solution:
In this program, we will generate a floating-point random number using the gen_range() method between the specified range and print the result.
Add random external library to your project
-
Create your project using the below command.
$cargo new random --bin
-
Goto the project folder cd random and edit Cargo.toml file.
$random>nano Cargo.toml
-
Then add dependency in Cargo.toml file
[dependencies]
rand = "0.5.5"
-
After that, build your project using the below command
$random>cargo build
-
Then execute your project after modification in the src/main.rs source file.
$random>cargo run
Program/Source Code:
The source code to generate a floating-point random number between the specific range is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.
// Rust program to generate a floating-point
// random number between a specific range.
use rand::Rng;
fn main() {
let mut range = rand::thread_rng();
println!("Float random number: {}", range.gen_range(10.5,20.6));
}
Output:
$random> cargo run
Compiling random v0.1.0 (/home/arvind/Desktop/rust/random)
Finished dev [unoptimized + debuginfo] target(s) in 0.29s
Running `target/debug/random`
Float random number: 15.180497931347297
Explanation:
In the above program, we imported the "rand" library to our project for generating random numbers. We imported the "rand" library using the below line:
use rand::Rng;
In the main() function, we generated a floating-point integer number between the specified range using the gen_range() method and printed the result.
Rust Random Numbers Programs »