Picking a random number from a set in C++

G

gilly_54

Guest
So I want this bit of code in my program to pick ONE number for a variable from a set...Let's call the variable num for now...
The set I want it to pick from is 0, 2, 6, 8. So in the end, num HAS to be 0, 2, 6, 8. It can't be empty or anything else.
I tried using rand() but I can only get it to pick from a series of numbers so far, like from 0 to 8...not very helpful if it picks a number like 1 or 5 every now and then...
Code:
srand (unsigned(time(NULL))); //Random seed generated every time
num = rand() % 8 + 0;
if (num == 0 ||num == 2||num == 6 ||num == 8){
	cout<<num<<endl; //Print if num = 0, 2, 6 or 8...Let's say this HAS to print otherwise armageddon will be upon us :P
}
 
Last edited:
I managed to figure it out...but if another hopeless soul faces this problem and googles it, perhaps this thread will show up. So I'll post the solution :)
Code:
int set[4] = {0,2,6,8};

srand (unsigned(time(NULL)));
num = set[rand() % 4];
cout << num << endl;
 
Back
Top