go语言中的math库

go语言中的math库

首先没有编译器的可以通过这个网址进行敲代码:Lightly

简介

Go语言的 math 包提供了许多数学函数和常量,涵盖了各种数学运算。以下是一些常用函数的介绍:

Abs(x float64) float64:返回x的绝对值。

Ceil(x float64) float64:返回不小于x的最小整数值。

Cos(x float64) float64:返回x的余弦值(x以弧度为单位)。

Exp(x float64) float64:返回自然指数e的x次幂。

Floor(x float64) float64:返回不大于x的最大整数值。

Log(x float64) float64:返回x的自然对数。

Max(x, y float64) float64:返回x和y中的最大值。

Min(x, y float64) float64:返回x和y中的最小值。

Mod(x, y float64) float64:返回x除以y的余数。

Pow(x, y float64) float64:返回x的y次幂。

Round(x float64) float64:返回四舍五入到最接近的整数值。

Sin(x float64) float64:返回x的正弦值(x以弧度为单位)。

Sqrt(x float64) float64:返回x的平方根。

Tan(x float64) float64:返回x的正切值(x以弧度为单位)。

除此之外,math 包还包括一些常量,如:

math.E:自然常数e。

math.Pi:圆周率π。

math.Sqrt2:2的平方根。

math.SqrtE:自然常数e的平方根。

math.SqrtPi:圆周率π的平方根。

math.Ln2:2的自然对数。

math.Log2E:以2为底的自然对数e的倒数。

math.Log10E:以10为底的自然对数e的倒数。

math.MaxFloat64:float64类型能够表示的最大值。

math.SmallestNonzeroFloat64:float64类型中能够表示的最小非零值。

需要注意的是,由于浮点数计算可能存在舍入误差,因此在进行精确计算时需考虑这些误差。

例题

1. 求两点之间的距离

package main

import (
	"fmt"
	"math"
)

func distance(x1, y1, x2, y2 float64) float64 {
    
    
	a := x2 - x1
	b := y2 - y1
	return math.Sqrt(a*a + b*b)
}

func main() {
    
    
	fmt.Println(distance(0, 0, 3, 4))
}

运行结果:
在这里插入图片描述

2. 求一个数组的平均值

package main

import (
	"fmt"
	"math"
)

func average(numbers []float64) float64 {
    
    
	total := 0.0
	for _, value := range numbers {
    
    
		total += value
	}
	return total / float64(len(numbers))
}

func main() {
    
    
	numbers := []float64{
    
    98, 93, 77, 82, 83}
	fmt.Println("Average:", math.Round(average(numbers)*100)/100)
}

运行结果:
在这里插入图片描述

3. 求三角形面积

package main

import (
	"fmt"
	"math"
)

func triangleArea(a, b, c float64) float64 {
    
    
	s := (a + b + c) / 2.0
	return math.Sqrt(s * (s - a) * (s - b) * (s - c))
}

func main() {
    
    
	a := 3.0
	b := 4.0
	c := 5.0
	fmt.Println("Triangle area:", triangleArea(a, b, c))
}

运行结果:

在这里插入图片描述

4. 求正弦函数的值

package main

import (
	"fmt"
	"math"
)

func sin(x float64) float64 {
    
    
	return math.Sin(x)
}

func main() {
    
    
	x := math.Pi / 6
	fmt.Printf("sin(%v) = %v\n", x, sin(x))
}

运行结果:
在这里插入图片描述

5. 求对数函数的值

package main

import (
   "fmt"
   "math"
)

func log(x float64) float64 {
    
    
   return math.Log10(x)
}

func main() {
    
    
   x := 100.0
   fmt.Printf("log(%v) = %v\n", x, log(x))
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_51447496/article/details/130115419