开发者

how to get random nubmer +1 or -1 (just need it for "+" or "-")

开发者 https://www.devze.com 2023-02-16 07:58 出处:网络
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;

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

精彩评论

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

关注公众号