【问题标题】:Randomly generate "-1" or "1" - Shortest Method随机生成“-1”或“1”——最短方法
【发布时间】:2013-02-11 04:14:22
【问题描述】:

我需要随机生成“-1”或“1”来随机确定数字的符号...最短的方法是什么?我目前正在使用它,但它似乎很长:

sign = (round((arc4random() % 2)))-((round((arc4random() % 2))) == 0);

【问题讨论】:

    标签: ios objective-c random integer sign


    【解决方案1】:
    short int randomNumber () {
    return arc4random() % 2 ? 1 : -1;
    }
    

    【讨论】:

      【解决方案2】:

      arc4random_uniform(2) ? -1 : 1 呢?

      arc4random_uniform(2)*2 - 1

      【讨论】:

      • 很好,它就像一个随机二进制操作
      • 哦,非常好!乘以2减1,没想到! :)
      • arc4random_uniform() 将返回一个小于upper_bound 的均匀分布的随机数。 它避免了模偏差。见arc4random manpage
      • 另一种可能性(不值得另一个答案):static const int tmp[] = {-1, 1}; return tmp[arc4random_uniform(2)];
      • @twalberg 这也很酷!如果数组不仅仅是 2 个数字(即 -1 和 d 1),那么数组将非常有用
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-14
      • 1970-01-01
      • 1970-01-01
      • 2022-05-29
      相关资源
      最近更新 更多