Golang的math包常用方法
作者:尹正傑
版權聲明:原創作品,謝絕轉載!否則將追究法律責任。
一.math包中定義的常量
package main import ( "fmt" "math" ) func main() { fmt.Printf("float64的最大值是:%.f\n", math.MaxFloat64) fmt.Printf("float64的最小值是:%.f\n", math.SmallestNonzeroFloat64) fmt.Printf("float32的最大值是:%.f\n", math.MaxFloat32) fmt.Printf("float32的最小值是:%.f\n", math.SmallestNonzeroFloat32) fmt.Printf("Int8的最大值是:%d\n", math.MaxInt8) fmt.Printf("Int8的最小值是:%d\n", math.MinInt8) fmt.Printf("Uint8的最大值是:%d\n", math.MaxUint8) fmt.Printf("Int16的最大值是:%d\n", math.MaxInt16) fmt.Printf("Int16的最小值是:%d\n", math.MinInt16) fmt.Printf("Uint16的最大值是:%d\n", math.MaxUint16) fmt.Printf("Int32的最大值是:%d\n", math.MaxInt32) fmt.Printf("Int32的最小值是:%d\n", math.MinInt32) fmt.Printf("Uint32的最大值是:%d\n", math.MaxUint32) fmt.Printf("Int64的最大值是:%d\n", math.MaxInt64) fmt.Printf("Int64的最小值是:%d\n", math.MinInt64) //fmt.Println("Uint64的最大值是:", math.MaxUint64) fmt.Printf("圓周率默認為:%.200f\n", math.Pi) }
二.math包中常用的方法
package main import ( "fmt" "math" ) func main() { /* 取絕對值,函數簽名如下: func Abs(x float64) float64 */ fmt.Printf("[-3.14]的絕對值為:[%.2f]\n", math.Abs(-3.14)) /* 取x的y次方,函數簽名如下: func Pow(x, y float64) float64 */ fmt.Printf("[2]的16次方為:[%.f]\n", math.Pow(2, 16)) /* 取余數,函數簽名如下: func Pow10(n int) float64 */ fmt.Printf("10的[3]次方為:[%.f]\n", math.Pow10(3)) /* 取x的開平方,函數簽名如下: func Sqrt(x float64) float64 */ fmt.Printf("[64]的開平方為:[%.f]\n", math.Sqrt(64)) /* 取x的開立方,函數簽名如下: func Cbrt(x float64) float64 */ fmt.Printf("[27]的開立方為:[%.f]\n", math.Cbrt(27)) /* 向上取整,函數簽名如下: func Ceil(x float64) float64 */ fmt.Printf("[3.14]向上取整為:[%.f]\n", math.Ceil(3.14)) /* 向下取整,函數簽名如下: func Floor(x float64) float64 */ fmt.Printf("[8.75]向下取整為:[%.f]\n", math.Floor(8.75)) /* 取余數,函數簽名如下: func Floor(x float64) float64 */ fmt.Printf("[10/3]的余數為:[%.f]\n", math.Mod(10, 3)) /* 分別取整數和小數部分,函數簽名如下: func Modf(f float64) (int float64, frac float64) */ Integer, Decimal := math.Modf(3.14159265358979) fmt.Printf("[3.14159265358979]的整數部分為:[%.f],小數部分為:[%.14f]\n", Integer, Decimal) }