Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

来源:原创题
难度:★

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

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

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.