I was wondering what the way is to get a random number with a range of 1-6, using the rand() method. This is to simulate a dice roll needed for me to find the average of 3 dice rolls so the type will be double.
random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.
random() function generates random floating numbers in the range[0.1, 1.0).
In this program we call the srand () function with the system clock, to initiate the process of generating random numbers. And the rand () function is called with module 10 operator to generate the random numbers between 1 to 10. srand(time(0)); // Initialize random number generator.
This is a simple example to generate randoms between 1 to 6, I think you can figure the rest
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
srand(time(0));
std::cout << (rand() % 6 + 1) <<std::endl;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With