Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

golang,go语言两数相除之后为什么得到整数?如何得到浮点数?

package main

import "fmt"

func main() {
    var slice01 = [...]int{1,2,3}
    var aa = len(slice01)
    var bb = (aa / 2) // var bb float32 = (aa / 2) 这样会报错
    fmt.Println(aa, bb)
    // 打印结果:3 1
    // 如何能打印出来 1.5?
    
}

谢谢帮助


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

大多数语言都是如此吧。
一般整数和浮点数运算会隐式地将整数转为浮点数,因此你可以如下计算得到浮点数:

aa * 1.0 / 2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...