doutonghang2761 2018-08-30 10:22
浏览 439

获取错误未定义:使用Math / rand库时Go语言中的数学

When I run the following code it gives the error undefined math in the line

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

However when i run only one method (foo or boo) no error is given.

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))
    }
  • 写回答

1条回答 默认 最新

  • dthy81285 2018-08-30 11:55
    关注

    As Volker said in the comments, importing math/rand does not import math. You have to import "math" explicitely.

    Go is not an interpreted language. Imports are resolved at compile time, not at runtime. It doesn't matter which of the two functions you call, or even if you don't call any of them. The code doesn't compile either way:

    $ 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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分