Xcode中如何使用While循环防止随机数出现相同的数字?
我希望它不断生成不同的随机数。如何使用While语句?
int randomnumber = (arc4random() % 188)+1;
if ([myArray containsObject:[NSNumber numberWithInt:randomnumber]])
{
NSLog(@"Yes, they are the same");
randomnumber = (arc4random() % 188)+1;
}
else
{
NSLog(@"No, they are not the same");
}
[myArray addObject:[NSNumber numberWithInt:randomnumber]];
I want it keeps generating different random number. How to use While statement?
int randomnumber = (arc4random() % 188)+1;
if ([myArray containsObject:[NSNumber numberWithInt:randomnumber]])
{
NSLog(@"Yes, they are the same");
randomnumber = (arc4random() % 188)+1;
}
else
{
NSLog(@"No, they are not the same");
}
[myArray addObject:[NSNumber numberWithInt:randomnumber]];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许是这样的。它循环直到找到不在数组中的数字。
如果您需要大量随机数,您可以将整个过程放入另一个循环中,该循环根据您需要的不同数字运行多少轮。
Maybe something like this. It loops until it finds a number that's not in the array.
If you need lots of random numbers, you can put the whole thing into another loop that runs for as many rounds as you need distinct numbers.
NSMutableSet 不允许重复。
NSMutableSet wont allow dublicate.