开发者

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜