iOS - 随机选择一个数字

时间:2014-02-06 12:30:38

标签: ios objective-c random

我正在尝试为x位置选择一个随机数,但我有一个随机方法的问题,这是我的代码:

        int xPosition = [self placeRandomEnemy];
        car3.position = CGPointMake(xPosition, CGRectGetMidY(self.frame));

//随机方法:

- (int)placeRandomEnemy {

    int x1 = 60;

    int x2 = 160 ;

    int x3 = 260;

  return arc4random() %  (x1 , x2 , x3);

}

xPosition应该是x1或x2或x3中的数字,但我的方法不起作用。

3 个答案:

答案 0 :(得分:3)

int placeRandomEnemey() {
    static int xPos[] = { 60, 160, 260 };
    return xPos[arc4random_uniform(sizeof(xPos) / sizeof(xPos[0]))];
}

这将返回60160260


它可以这样使用:

car3.position = CGPointMake(placeRandomEnemy(), CGRectGetMidY(self.frame));

答案 1 :(得分:1)

替换return arc4random() % (x1 , x2 , x3);

switch (arc4random_uniform(3)) {
        case 0:
            return x1;
            break;
        case 1:
            return x2;
            break;
        default:
            return x3;
            break;
    }

答案 2 :(得分:0)

您可以在数组中获取这些值,然后您可以像这样获得随机索引。

NSArray *arr = [NSArray arrayWithObjects:@"1",@"2",@"3", nil];


int rand= arc4random()%[arr count];
NSLog(@"%d",rand);

现在你可以获得对象at random索引的值。

int value = [[arr objectAtIndex:rand] intValue];

这是一个简单的解决方案。

可能有不同的方法来获得它。

相关问题