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)
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) }
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) } }
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!