how to get random nubmer +1 or -1 (just need it for "+" or "-")
i need开发者_开发百科 random number but only +1 or -1 (to have force direction defined in box2d) how to get this only two random numbers? thank you!
int random = arc4rand()%2 ? -1 : 1;
int result = (WhateverRandomNumbersComeFromInObjectiveC() >= 0.5) ? 1 : -1;
#include <stdlib.h>
(arc4random() % 2) * 2 - 1
- arc4random() gives a random integer
- (arc4random() % 2) makes it be 0 or 1
- (arc4random() % 2) * 2 makes it be 0 or 2
- (arc4random() % 2) * 2 - 1 gives you -1 or 1
精彩评论