Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate random number between 3 determinated values c++

my problem here is simple, all i want is a rand() that pick randomly between my values, that are 2, 4, 6, then return it.

All i tried is:

int ene = (rand() % 2)? 2: 4;

it works, returns me 2 or 4, but i dont know how to add the 6.
i want a random, that returns me 2, 4 or 6.
Any answer will be received

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

std::srand(std::time(0)); 
    int options[] = {2, 4, 6};
    int randomIndex = std::rand() % 3;
    int result = options[randomIndex];

you can try using time as seed for random generator

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading