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

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

问题描述

以下GO程序给出错误:

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

程序:

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?

Why cant I use an int in a type of float64 ?

推荐答案

替换

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

作者

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

引用规范:

当不同的数字类型混合在一个数字中时,需要进行转换 表达式或赋值.例如,int32和int不相同 键入,即使它们在特定大小上可能具有相同的大小 建筑.

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常见问题解答对此有更多要说的.

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指出,在这种情况下,以下内容就足够了:

@jnml points out that, in this case, the following is enough:

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

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

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