Search code examples
c++randomintegernumbers

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


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