Home > Backend Development > Golang > How to generate negative random numbers in Golang?

How to generate negative random numbers in Golang?

王林
Release: 2024-06-03 20:01:00
Original
908 people have browsed it

To generate negative random numbers in Go, you need to use the math/rand package. The specific method is: single negative random number: randomNumber = -1 * rand.Float64() negative random number sequence: randomNumber = -10 + rand.Intn( 10)

如何在 Golang 中生成负随机数?

How to generate negative random numbers in Golang?

Generating negative random numbers in Golang requires the math/rand package. This package provides functions for generating random numbers and pseudo-random sequences.

Generate a single negative random number

To generate a negative random number in the range -1 to 0, you can use the following code:

import (
    "math/rand"
    "time"
)

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

    // 生成一个范围在 -1 到 0 之间的随机数
    randomNumber := -1 * rand.Float64()

    // 打印随机数
    fmt.Println(randomNumber)
}
Copy after login

Generate a sequence of negative random numbers

To generate a sequence of negative random numbers, you can use rand.Intn from the math/rand package function or rand.Float64 function. For example, to generate 10 negative random numbers in the range -10 to 0, you would use the following code:

import (
    "math/rand"
    "time"
)

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

    // 生成 10 个范围在 -10 到 0 之间的随机数
    for i := 0; i < 10; i++ {
        randomNumber := -10 + rand.Intn(10)
        fmt.Println(randomNumber)
    }
}
Copy after login

The above code will generate 10 random numbers and print them to the console.

The above is the detailed content of How to generate negative random numbers 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