Home  >  Article  >  Backend Development  >  How to generate random integers within a specified range in Golang?

How to generate random integers within a specified range in Golang?

WBOY
WBOYOriginal
2024-06-04 09:19:01890browse

In Golang, use the Intn function in the rand package to generate a random integer within a specified range. The syntax is func Intn(n int) int, where n is an inclusive upper limit of random integers. By setting a random number seed and using Intn(100) + 1, you can generate a random integer between 1 and 100 (inclusive). However, it should be noted that the random integers generated by Intn are pseudo-random and cannot generate random integers with a specific probability distribution.

如何在 Golang 中生成指定范围的随机整数?

#How to generate a random integer within a specified range in Golang?

Generating random integers within a specified range in Golang is very simple, you can use the Intn function in the rand package.

Code syntax:

func Intn(n int) int

Where, n is the upper limit of random integers (not inclusive).

Practical case:

Let us generate a random integer between 1 and 100 (inclusive):

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    // 设置随机数种子
    rand.Seed(time.Now().UnixNano())

    // 生成一个在 1 到 100(含)之间的随机整数
    num := rand.Intn(100) + 1

    fmt.Println(num)
}

Run the above program, You will see a random integer between 1 and 100 printed on the command line.

Notes:

  • #Intn The random integers generated by the function are pseudo-random, which means they are generated by the algorithm rather than Generated from a truly random source such as a coin toss.
  • Intn The function cannot generate random integers with a specific probability distribution (such as the normal distribution). For such use cases, you need to use other random number generation methods.

The above is the detailed content of How to generate random integers within a specified range in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn