2 回答

拉風的咖菲貓
TA貢獻1995條經驗 獲得超2個贊
int(math.Round(f))在 Go 中將浮點數轉換為 int 時,您可以使用舍入到最接近的整數。當浮點數設置為字節或符文時,小數也會被丟棄。當它設置為字符串或布爾值時,不會發生截斷。
package main
import (
. "fmt"
. "math"
)
func main() {
f := 3.6
c := []interface{}{byte(f), f, int(Round(f)), rune(f), Sprintf("%.f", f), f != 0}
checkType(c)
}
func checkType(s []interface{}) {
for k, _ := range s {
Printf("%T %v\n", s[k], s[k])
}
}
Round 返回最接近的整數,從零四舍五入。請參閱https://golang.org/pkg/math/#Round。請參閱https://stackoverflow.com/a/61503758/12817546。
f := 3.6截斷為“uint8 3”,f為“float64 3.6”,int(Round(f))向上舍入為“int 4”, rune(f)截斷為“int32 3”, Sprintf("%.f", f)為“string 3.6”并f != 0輸出“bool true”。
- 2 回答
- 0 關注
- 533 瀏覽
添加回答
舉報
0/150
提交
取消