Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How I can get random value from 1 to 12? [duplicate]

Tags:

c++

random

How I can get in C++ random value from 1 to 12?

So I will have 3, or 6, or 11?

like image 763
MicheleIce Avatar asked Nov 28 '22 15:11

MicheleIce


2 Answers

Use the following formula:

M + rand() / (RAND_MAX / (N - M + 1) + 1), M = 1, N = 12

and read up on this FAQ.

Edit: Most answers on this question do not take into account the fact that poor PRN generators (typically offered with the library function rand()) are not very random in the low order bits. Hence:

rand() % 12 + 1

is not good enough.

like image 130
dirkgently Avatar answered Dec 06 '22 19:12

dirkgently


#include <iomanip>
#include <iostream>
#include <stdlib.h>
#include <time.h>

// initialize random seed
srand( time(NULL) );

// generate random number
int randomNumber = rand() % 12 + 1;

// output, as you seem to wan a '0'
cout << setfill ('0') << setw (2) << randomNumber;

to adress dirkgently's issue maybe something like that would be better?

// generate random number
int randomNumber = rand()>>4; // get rid of the first 4 bits

// get the value
randomNumer = randomNumer % 12 + 1;

edit after mre and dirkgently's comments

like image 35
f4. Avatar answered Dec 06 '22 19:12

f4.