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

WBOY
Release: 2024-06-04 09:19:01
Original
949 people have browsed it

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
Copy after login

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)
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!