floating-point - 常量截断为整数

标签 floating-point go syntax-error

以下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) 吗? 整数(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/42940810/

相关文章:

c++ - 在浮点精度成为问题之前可以将多少个 float 加在一起

c++ - 为什么mpfr_printf与printf的十六进制 float (%a转换说明符)不同?

go - 类型开关不检测 float32

set - 为什么我在 Scheme 中的 adjoin-set 过程会返回错误?

javascript - "elseif"Javascript 附近的语法错误

c - 书错?函数中不必要的分号(Head First C 示例,Griffiths & Griffiths 2012)

math - float 学坏了吗?

programming-languages - 'systems language' 是什么意思?

go - 使用接口(interface)设置具体结构的值

python - 在 python 中迭代时遇到问题