0

我希望它不断生成不同的随机数。如何使用 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]];
4

2 回答 2

1

也许是这样的。它循环直到找到不在数组中的数字。

int randomnumber = (arc4random() % 188)+1; 

while ([myArray containsObject:[NSNumber numberWithInt:randomnumber]])
{
    NSLog(@"Yes, they are the same");
    randomnumber = (arc4random() % 188)+1;
}

[myArray addObject:[NSNumber numberWithInt:randomnumber]];

如果您需要大量随机数,您可以将整个事情放入另一个循环中,该循环会根据您需要的不同数字运行尽可能多的轮次。

于 2011-07-23T14:57:47.550 回答
0

NSMutableSet 不允许重复。

    NSMutableSet * numberWithSet = [[NSMutableSet alloc]initWithCapacity:20]

    while ([numberWithSet count] < 20 ) {

        NSNumber * randomNumber = [NSNumber numberWithInt:(arc4random() % 23 + 1)];

        [numberWithSet addObject:randomNumber];

    }

        NSLog(@"numberWithSet : %@ \n\n",numberWithSet);

    [numberWithSet release];

    `arc4random() % 22 + 1` will give you numbers between 1 and 22 including both of them but not 23.
于 2011-07-23T15:00:02.160 回答