常量1截断为整数? [英] Constant 1 truncated to integer?

查看:195
本文介绍了常量1截断为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

  package main 
const a = 1.000001
const base = 0
const b = a + base
func main(){
f(b)
}
func f(int){}





  $ go运行a.go 
$命令行参数
./a.go:4:常量1被截断为整数

它是说1被截断了吗?或者1不能被截断?有人回答说上面的代码不能编译,因为 b 是一个 float64 。但为什么这样编译:

  package main 
importfmt
const a = 1.000001
const b = a-0.000001
func main(){
fmt.Printf(%T%v \ n,a,a)
fmt.Printf( T%v \ n,b,b)
f(b)
}
func f(int){}





  $ go运行a.go 
float64 1.000001
float64 1

b 在这里是一个 float64 ,但它可以传递给 f 博客文章关于这个最近我建议你阅读。



从介绍


Go是一种静态类型的语言,它不允许
混合数字类型的操作。您不能将float64添加到int中,或者将int32
添加到int中。然而,写出1e6 * time.Second或math.Exp(1)或
甚至1 <<('\ t'+ 2.0)是合法的。在Go中,与变量不同,常量与常规数字非常相似。这篇文章解释了为什么是这样以及
表示什么。


TLDR - 常量在Go中是无类型的。他们的类型只是在最后时刻才能形成。

这解释了上述问题。给定

  func f(int){} 

然后

  f(1)// ok 
f(1.000) // OK
f(1.0E6)// OK
f(1.0001)// BAD


Why wont this code compile?

package main
const a = 1.000001
const base = 0
const b = a+base
func main() {
    f(b)
}
func f(int) {}

$ go run a.go
# command-line-arguments
./a.go:4: constant 1 truncated to integer

It's saying that 1 is truncated? Or that 1 cannot be truncated? Which 1 is it talking about?

Someone answered the above code doesn't compile because b is a float64. But then why does this compile:

package main
import "fmt"
const a = 1.000001
const b = a-0.000001
func main() {
    fmt.Printf("%T %v\n",a,a)
    fmt.Printf("%T %v\n",b,b)
    f(b)
}
func f(int) {}

$ go run a.go 
float64 1.000001
float64 1

? b is a float64 here, but it can be passed to f.

解决方案

The go team made a blog post about this recently which I suggest you read.

From the introduction

Go is a statically typed language that does not permit operations that mix numeric types. You can't add a float64 to an int, or even an int32 to an int. Yet it is legal to write 1e6*time.Second or math.Exp(1) or even 1<<('\t'+2.0). In Go, constants, unlike variables, behave pretty much like regular numbers. This post explains why that is and what it means.

TLDR - constants are untyped in Go. Their type is only crystallized at the last moment.

That explains your problem above. Given

func f(int) {}

Then

f(1) // ok
f(1.000) // OK
f(1.0E6) // OK
f(1.0001) // BAD

这篇关于常量1截断为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆