GO lang - 常量被截断为整数 [英] GO lang - constant truncated to integer
问题描述
./ fft.go:13:常量-6.28319截断为整数
./fft.go:13:在赋值
中不能使用-7 * k / N(类型为int)
程序:
package main
pre>
import(
数学
fmt
)
func main(){
fmt.Println(Hello world,math.E)
var k,N int = 1,10
var ans float64 = 0
var c float64 =(-2.0 * math.Pi * k)/ N
x:= make([] float64,N)
for i:= 0;我< LEN(X); i ++ {
x [i] = 1
}
ans = 0
for i:= 0;我< N; i ++ {
ans + = x [i] * math.E
}
fmt.Println(ans)
}
为什么不能在
$ b $ <$ p $ <$ p $ <$ p $ <$ p code> var c float64 =(-2.0 * math.Pi * k)/ Nfloat64 $ c类型中使用
int
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
不同的数字类型在
表达式或赋值中混合使用时,需要进行转换。例如,int32和int不是相同的
类型,即使它们在特定的
架构上可能具有相同的大小。
Go使用静态类型,不会自动在数字类型之间进行转换。原因可能是为了避免一些错误。例如,什么值和什么类型应该 float64(2.5)* int(2)
yield?如果结果是 int(5)
? INT(4)
? float64(5.0)
?在Go中,这不是问题。 Go FAQ对此有多说。
@jnml指出,在这种情况下,以下就足够了:
var c float64 = -2 * math.Pi / float64(N)
The following GO program gives the error:
./fft.go:13: constant -6.28319 truncated to integer
./fft.go:13: cannot use -7 * k / N (type int) as type float64 in assignment
Program:
package main
import (
"math"
"fmt"
)
func main() {
fmt.Println("Hello world ",math.E)
var k, N int = 1, 10
var ans float64 = 0
var c float64 = (-2.0 * math.Pi * k) / N
x := make([]float64,N)
for i := 0; i < len(x); i++ {
x[i] = 1
}
ans = 0
for i := 0; i < N; i++ {
ans += x[i] * math.E
}
fmt.Println(ans)
}
Why cant I use an int
in a type of float64
?
Replace
var c float64 = (-2.0 * math.Pi * k) / N
by
var c float64 = (-2.0 * math.Pi * float64(k)) / float64(N)
To quote the spec:
Conversions are required when different numeric types are mixed in an expression or assignment. For instance, int32 and int are not the same type even though they may have the same size on a particular architecture.
Go uses static typing and doesn't automatically convert between numeric types. The reason is probably to avoid some errors. For instance, what value and what type should float64(2.5) * int(2)
yield? Should the result be int(5)
? int(4)
? float64(5.0)
? In Go, this isn't an issue. The Go FAQ has more to say on this.
@jnml points out that, in this case, the following is enough:
var c float64 = -2 * math.Pi / float64(N)
这篇关于GO lang - 常量被截断为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!