Golang的math包常用方法
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
一.math包中定义的常量
package main import ( "fmt" "math" ) func main() { fmt.Printf("float64的最大值是:%.f ", math.MaxFloat64) fmt.Printf("float64的最小值是:%.f ", math.SmallestNonzeroFloat64) fmt.Printf("float32的最大值是:%.f ", math.MaxFloat32) fmt.Printf("float32的最小值是:%.f ", math.SmallestNonzeroFloat32) fmt.Printf("Int8的最大值是:%d ", math.MaxInt8) fmt.Printf("Int8的最小值是:%d ", math.MinInt8) fmt.Printf("Uint8的最大值是:%d ", math.MaxUint8) fmt.Printf("Int16的最大值是:%d ", math.MaxInt16) fmt.Printf("Int16的最小值是:%d ", math.MinInt16) fmt.Printf("Uint16的最大值是:%d ", math.MaxUint16) fmt.Printf("Int32的最大值是:%d ", math.MaxInt32) fmt.Printf("Int32的最小值是:%d ", math.MinInt32) fmt.Printf("Uint32的最大值是:%d ", math.MaxUint32) fmt.Printf("Int64的最大值是:%d ", math.MaxInt64) fmt.Printf("Int64的最小值是:%d ", math.MinInt64) //fmt.Println("Uint64的最大值是:", math.MaxUint64) fmt.Printf("圆周率默认为:%.200f ", math.Pi) }
二.math包中常用的方法
package main import ( "fmt" "math" ) func main() { /* 取绝对值,函数签名如下: func Abs(x float64) float64 */ fmt.Printf("[-3.14]的绝对值为:[%.2f] ", math.Abs(-3.14)) /* 取x的y次方,函数签名如下: func Pow(x, y float64) float64 */ fmt.Printf("[2]的16次方为:[%.f] ", math.Pow(2, 16)) /* 取余数,函数签名如下: func Pow10(n int) float64 */ fmt.Printf("10的[3]次方为:[%.f] ", math.Pow10(3)) /* 取x的开平方,函数签名如下: func Sqrt(x float64) float64 */ fmt.Printf("[64]的开平方为:[%.f] ", math.Sqrt(64)) /* 取x的开立方,函数签名如下: func Cbrt(x float64) float64 */ fmt.Printf("[27]的开立方为:[%.f] ", math.Cbrt(27)) /* 向上取整,函数签名如下: func Ceil(x float64) float64 */ fmt.Printf("[3.14]向上取整为:[%.f] ", math.Ceil(3.14)) /* 向下取整,函数签名如下: func Floor(x float64) float64 */ fmt.Printf("[8.75]向下取整为:[%.f] ", math.Floor(8.75)) /* 取余数,函数签名如下: func Floor(x float64) float64 */ fmt.Printf("[10/3]的余数为:[%.f] ", math.Mod(10, 3)) /* 分别取整数和小数部分,函数签名如下: func Modf(f float64) (int float64, frac float64) */ Integer, Decimal := math.Modf(3.14159265358979) fmt.Printf("[3.14159265358979]的整数部分为:[%.f],小数部分为:[%.14f] ", Integer, Decimal) }