2013-04-22 54 views
6

下圍棋程序給出了錯誤: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

+0

我真的喜歡這些漂亮的golang錯誤信息......他們包括人在討論,不只是機器與機器聊天......與其他語言寫作相比,這是多麼的快樂......並且主動讓寫golang代碼變得更有趣 – 2017-09-14 00:09:27

回答

10

更換

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 FAQ有more to say


@jnml指出,在這種情況下,以下就足夠了:

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

'c:= -2 * math.Pi/float64(N)'就夠了 – zzzz 2013-04-22 15:58:35

+3

在這種情況下,是的。但我認爲問題是關於打字,而不是讓這個特定的程序起作用。所以,儘管'c:= ...'是更好的代碼,我認爲它有點讓人困惑。 – scvalex 2013-04-22 16:00:38

+0

Ehm,忽略'c:='部分,這只是出於習慣。關鍵是'float64'的三個實例中有兩個是多餘的,'k * floatConst'可以使用整數'k' - 這是一個「理想」數字。 – zzzz 2013-04-22 16:06:09