A Tour of Go Numeric Constants

川长思鸟来 2022-01-07 07:05 296阅读 0赞

Numeric constants are high-precision values.

An untyped constant takes the type needed by its context.

Try printing needInt(Big) too.

  1. package main
  2. import "fmt"
  3. const (
  4. Big = 1 << 100
  5. Small = Big >> 99
  6. )
  7. func needInt(x int) int {
  8. return x*10 + 1
  9. }
  10. func needFloat(x float64) float64{
  11. return x * 0.1
  12. }
  13. func main() {
  14. fmt.Println(needInt(Small))
  15. fmt.Println(needFloat(Small))
  16. fmt.Println(needFloat(Big))
  17. }
  18. package main
  19. import "fmt"
  20. const (
  21. Big = 1 << 100
  22. Small = Big >> 99
  23. )
  24. func needInt(x int) int {
  25. return x*10 + 1
  26. }
  27. func needFloat(x float64) float64{
  28. return x * 0.1
  29. }
  30. func main() {
  31. fmt.Println(Small);
  32. var intVariable int = 1
  33. //var float32Variable float32 = 1.2
  34. fmt.Println(needInt(Small))
  35. // constant 1267650600228229401496703205376 overflows int
  36. //fmt.Println(needInt(Big))
  37. fmt.Println(needFloat(Small))
  38. fmt.Println(needFloat(Big))
  39. //go语言对类型的要求是很严格的,所以你不能传递int到float中或者float到int
  40. fmt.Println(needInt(intVariable))
  41. //cannot use float32Variable (type float32) as type int in argument to needInt
  42. //fmt.Println(needInt(float32Variable))
  43. //cannot use intVariable (type int) as type float64 in argument to needFloat
  44. //fmt.Println(needFloat(intVariable))
  45. //cannot use float32Variable (type float32) as type float64 in argument to needFloat
  46. //fmt.Println(needFloat(float32Variable))
  47. }

不过常量却相对宽容一些

  1. //constant 1267650600228229401496703205376 overflows int
  2. fmt.Println(Big);

转载于:https://www.cnblogs.com/ghgyj/p/4052714.html

发表评论

表情:
评论列表 (有 0 条评论,296人围观)

还没有评论,来说两句吧...

相关阅读