[英]iOS - Select a number randomly
我正在嘗試為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中的數字,但是我的方法不起作用。
int placeRandomEnemey() {
static int xPos[] = { 60, 160, 260 };
return xPos[arc4random_uniform(sizeof(xPos) / sizeof(xPos[0]))];
}
這將返回60
, 160
, 260
。
它可以這樣使用:
car3.position = CGPointMake(placeRandomEnemy(), CGRectGetMidY(self.frame));
替換return arc4random() % (x1 , x2 , x3);
同
switch (arc4random_uniform(3)) {
case 0:
return x1;
break;
case 1:
return x2;
break;
default:
return x3;
break;
}
您可以將這些值放入數組中,然后像這樣獲取隨機索引。
NSArray *arr = [NSArray arrayWithObjects:@"1",@"2",@"3", nil];
int rand= arc4random()%[arr count];
NSLog(@"%d",rand);
現在您可以at random
索引at random
獲取對象的值。
int value = [[arr objectAtIndex:rand] intValue];
這是簡單的解決方案。
可能有不同的方法來獲得它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.