How to choose a random case in a switch statement
I want to output several questions, but in a random order. How can I ask all questions randomly without repeating one?
for(int i=0; i<4; i++)
{
int question=rand()%4;
switch(question)
{
case 0:
NSL开发者_JAVA技巧og(@"What is your name");
break;
case 1:
NSLog(@"Who are you");
break;
case 2:
NSLog(@"What is your name");
break;
case 3:
NSLog(@"How do you do");
break;
case 4:
NSLog(@"Are you?");
break;
}
}
Keep the questions in an array. Shuffle the array at the start of questioning. Now pull one question from the list per iteration, ask it, get the answer, and continue until you run out of questions.
rand(3)
is pretty famous for having poor implementations that have pretty short cycles for the lower bits. Try using different bits, or use random(3)
instead. In fact, the rand(3)
man page on OS X says:
These interfaces are obsoleted by
random(3)
.
Also - % 4
can never be larger than 3, so your case 4
will never execute in this program.
It is recommended to use arc4random()
for a better algorithm with out the need to seed. Otherwise call srand
to seed your call to rand
.
精彩评论