2014-05-14 86 views
-1

我试图创建随机等级并将它们添加到test_scores数组。然后计算平均值。不匹配的类型float64和int

这个程序:

package main 

import (
    "fmt" 
    "math/rand" 
) 

func main() { 
    i := 0 
    var test_scores [5]float64 
    for i < len(test_scores) { 
     test_scores[i] = rand.Float64() 
     i++ 
    } 
    fmt.Println(test_scores) 

    var total float64 = 0 
    i = 0 
    for i < len(test_scores) { 
     total += test_scores[i] 
     i++ 
    } 
    fmt.Println(total) 
    fmt.Println(total/len(test_scores)) 
} 

生产:

main.go:24: invalid operation: total/5 (mismatched types float64 and int) 

这一个正常工作:

package main 

import (
    "fmt" 
    "math/rand" 
) 

func main() { 
    i := 0 
    var test_scores [5]float64 
    for i < len(test_scores) { 
     test_scores[i] = rand.Float64() 
     i++ 
    } 
    fmt.Println(test_scores) 

    var total float64 = 0 
    i = 0 
    for i < len(test_scores) { 
     total += test_scores[i] 
     i++ 
    } 
    fmt.Println(total) 
    fmt.Println(total/5) 
} 

唯一的区别是,在最后一行,我m使用固定的5和非工作人员,我正在使用len(test_scores)呼叫。

Len还返回一个整数,所以怎么了?

+3

你通常应该使用切片而不是数组。 – JimB

+0

“这个程序崩溃”是无益的。提问时请包含更多信息。 [我已将错误信息编辑为您的问题。] –

回答

3

当您直接在名为常量的源代码中编写5时。写作true也是如此。唯一的区别是前者是无类型常数,后者是类型不变。

不同之处在于,有没有关于应该有–什么类型true它永远是bool但在5这不是那么明显,取决于上下文的情况下歧义。

Go编译器会找出什么类型来给编译上的常量。详细情况在​​中描述。

编辑:

我意识到,有一个在我的答案是错误:true根据规格其实也无类型,因为其中一个类型从bool派生预计可以在任何地方使用。这意味着:

type MyBool bool 

func DoNothing(b MyBool) {} 

DoNothing(true) // true is coerced to MyBool 

虽然答案仍然有效。有类型和无类型常量之间的区别成立。

+0

关于常量的另一个有用的信息来源是[The Go博客:常量](https://blog.golang.org/constants)。 –

4

float64int是不同的类型,但在特定情况下允许转换。 (http://golang.org/ref/spec#Conversions

代码中的字面值5是无类型常量(http://golang.org/ref/spec#Constants),正确的类型由编译期间的表达式确定。

只需使用float64(len(test_scores))

+0

是的,我知道这一点。我想知道为什么'5'工作,并且'len(test_scores)'不会因为'len()'返回一个整数而'5'是一个整数。 – sergserg

+2

增加了对常量的引用。通读规格。它非常平易近人,并会回答所有这些细节。 – JimB

-1

此行

fmt.Printf("%T\n", total) 
fmt.Printf("%T\n", 5) 
fmt.Printf("%T\n", 5.0) 
fmt.Printf("%T\n", len(test_scores)) 

打印

float64 
int 
float64 
int 

也许编译器感知5为5.0。不管怎么样,你应该使用转换为float64。

+0

不,编译器将它们视为无类型常量,它只是在'fmt.Printf()'中计算时将它们转换为本地'int'和'float64' – JimB