Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, random number w/ range of 1-6

Tags:

c++

random

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.

like image 602
TLM Avatar asked Jan 12 '11 06:01

TLM


People also ask

How do you find the range of a random number?

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.

What is the range of random random ()?

random() function generates random floating numbers in the range[0.1, 1.0).

How do you generate a random number between 1 and 10 in C?

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.


1 Answers

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;
}
like image 59
Nylon Smile Avatar answered Oct 16 '22 09:10

Nylon Smile