gpt4 book ai didi

floating-point - 常量截断为整数

转载 作者:IT老高 更新时间:2023-10-28 13:10:27 24 4
gpt4 key购买 nike

以下 GO 程序报错:

./fft.go:13: constant -6.28319 truncated to integer
./fft.go:13: cannot use -7 * k / N (type int) as type float64 in assignment

程序:

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)
}

为什么我不能在 float64 类型中使用 int

最佳答案

替换

var c float64 = (-2.0 * math.Pi * k) / N

通过

var c float64 = (-2.0 * math.Pi * float64(k)) / float64(N)

引用 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 使用静态类型并且不会在数字类型之间自动转换。原因可能是为了避免一些错误。例如,float64(2.5) * int(2) 应该产生什么值和什么类型?结果应该是 int(5) 吗? int(4)? float64(5.0)?在 Go 中,这不是问题。 Go 常见问题解答有 more to say关于这个。


@jnml 指出,在这种情况下,以下内容就足够了:

var c float64 = -2 * math.Pi / float64(N)

关于floating-point - 常量截断为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16151199/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com