Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wingmeng opened this issue May 14, 2019 · 4 comments
Open

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

wingmeng opened this issue May 14, 2019 · 4 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented May 14, 2019

来源:原创题
难度:★

封装一个函数,接收一个整数参数 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

@liwenkang
Copy link

/**
 * @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;
}

@AMY-Y
Copy link

AMY-Y commented May 14, 2019

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

@liwenkang
Copy link

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

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

@AMY-Y
Copy link

AMY-Y commented May 15, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants