Visitar URL original
第 7 期(2019-05-14):n以内的随机数 · Issue #9 · fezaoduke/fe-practice-hard · GitHub
Skip to content

第 7 期(2019-05-14):n以内的随机数 #9

Description

@wingmeng

来源:原创题
难度:★

封装一个函数,接收一个整数参数 n ,返回 n 以内的随机整数 m (0 <= m < n)

/**
 * @param {number} n - 随机数最大范围
 */
function getRandomNum(n) {
  // 你的代码
}

参考答案:

// 方法1
function getRandomNum(n) {
  return Math.floor(Math.random() * n);
}

// 方法2
function getRandomNum(n) {
  return ~~(Math.random() * n);
}

// 方法3
function getRandomNum(n) {
  return (Math.random() * n) >>> 0;
}

// 方法4
function getRandomNum(n) {
  return Math.random() * n | 0;
}

本期最佳回答者: @AMY-Y

Activity

  1. liwenkang commented on May 14, 2019

    @liwenkang
    /**
     * @param {number} n - 随机数最大范围
     */
    function getRandomNum(n) {
        // 返回 n 以内的随机整数 m (0 <= m < n)
        // return Math.floor(Math.random() * n);
        // 返回 n 以内的随机数 m (0 <= m < n)
        return Math.random() * n;
    }
  2. AMY-Y commented on May 14, 2019

    @AMY-Y
    function getRandomNum(n){
            // 先判断是否为整数
            if(Math.round(n)===n){
                var integer=parseInt(Math.random()*n);
                return integer;
            }
        }
     getRandomNum(10);
    //小伙伴们,我感觉我这个没错啊,为啥控制台没反应呢?
  3. liwenkang commented on May 15, 2019

    @liwenkang
    function getRandomNum(n){
            // 先判断是否为整数
            if(Math.round(n)===n){
                var integer=parseInt(Math.random()*n);
                return integer;
            }
        }
     getRandomNum(10);
    //小伙伴们,我感觉我这个没错啊,为啥控制台没反应呢?

    实测没问题......╰( ̄▽ ̄)╭

  4. AMY-Y commented on May 15, 2019

    @AMY-Y

    哈哈哈,我的问题,return和console这些都有点忘了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions