我想生成一個介於1到10之間的隨機數。當用戶點擊「下一個」按鈕時,必須打印一個隨機問題並且問題不能重複。 問題是有時候問題在重複。 任何人都可以幫我或給一些參考或教程?生成1到10之間的隨機數而不重複
- (IBAction)nextQuestion:(id)sender
{
NSInteger randomNum = arc4random() %10 ;
int countCounter= counter++;
[self.btnNext setTitle:@"Next" forState:UIControlStateNormal];
if(countCounter==4)
{
self.btnNext.hidden=YES;
self.btnQuizDone.hidden=NO;
}
switch (arc4random()%10)
{
case 0:
{
NSLog(@"zero");
[lblQuestion setText:@"Q10:question number ten"];
}
break;
case 1:
{
NSLog(@"one");
[lblQuestion setText:@"Q2:question number two"];
}
break;
case 2:
{
NSLog(@"two");
[lblQuestion setText:@"Q6:question number six"];
}
break;
case 3:
{
NSLog(@"three");
[lblQuestion setText:@"Q5:question number five"];
}
break;
case 4:
{
NSLog(@"four");
[lblQuestion setText:@"Q3:question number three"];
}
break;
case 5:
{
NSLog(@"five");
[lblQuestion setText:@"Q9:question number nine"];
}
break;
case 6:
{
NSLog(@"six");
[lblQuestion setText:@"Q7:question number seven"];
}
break;
case 7:
{
NSLog(@"seven");
[lblQuestion setText:@"Q4:question number four"];
}
break;
case 8:
{
NSLog(@"eight");
[lblQuestion setText:@"Q1:question number one"];
}
break;
case 9:
{
NSLog(@"nine");
[lblQuestion setText:@"Q8:question number eight"];
}
break;
default:
break;
}
}
你忘了「break」在案例3 –
看看這個:http://stackoverflow.com/questions/196017/unique-random-numbers-in-o1這也是:http://stackoverflow.com/questions/1608181/unique-random-numbers- in-an-integer-array-in-the-c-programming-language – Spynet
你需要記住已經使用過的問題編號,沒有辦法繞過這個,afaik。 – martinstoeckli