登录
首页 >  Golang >  Go问答

出现错误未定义:使用 math/rand 库时 go lang 中的数学

来源:stackoverflow

时间:2024-04-18 15:57:31 473浏览 收藏

哈喽!今天心血来潮给大家带来了《出现错误未定义:使用 math/rand 库时 go lang 中的数学》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

当我运行以下代码时,它会在行中给出错误未定义的数学

fmt.println("the square root of 4 is",math.sqrt(4))

但是,当我仅运行一种方法(foo 或 boo)时,不会给出错误。

package main 

    import ("fmt"
           "math/rand")

    func main() {
        boo();
        foo();

    }

    func boo()  {
        fmt.Println("A number from 1-100",rand.Intn(100))
    }
    func foo() {

        fmt.Println("The square root of 4 is",math.Sqrt(4))
    }

解决方案


正如 volker 在评论中所说,导入 math/rand 不会导入 math。您必须明确地 import "math"

go 不是一种解释性语言。导入是在编译时解决的,而不是在运行时解决的。无论您调用这两个函数中的哪一个,或者即使您不调用其中任何一个,都没有关系。无论哪种方式,代码都无法编译:

$ nl -ba main.go 
 1  package main
 2
 3  import (
 4          "fmt"
 5          "math/rand"
 6  )
 7
 8  func main() {
 9  }
10
11  func boo() {
12          fmt.Println("A number from 1-100", rand.Intn(100))
13  }
14  func foo() {
15          fmt.Println("The square root of 4 is", math.Sqrt(4))
16  }
$ go build
# _/tmp/tmp.doCnt09SnR
./main.go:15:48: undefined: math

理论要掌握,实操不能落!以上关于《出现错误未定义:使用 math/rand 库时 go lang 中的数学》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>