Golang math.Remainder() 函数及示例

Golang math.Remainder() 函数及示例

Go 语言的 math 包提供了内置的支持,用于对数字执行基本常量和数学函数的操作。通过 math 包提供的 Remainder() 函数,您可以找到 a/b 的余数或 IEEE 754 浮点余数。因此,您需要在程序中使用 import 关键字添加 math 包以访问 Remainder() 函数。

语法:

func Remainder(a, b float64) float64
  • 如果在该函数中传递 -Inf 或 +Inf,例如 Remainder(-Inf, b) 或 Remainder(+Inf, b),则该函数将返回 NaN。
  • 如果在该函数中传递 NaN,例如 Remainder(NaN, b),则该函数将返回 NaN。
  • 如果在该函数中传递 b=0,例如 Remainder(a, 0),则该函数将返回 NaN。
  • 如果在该函数中传递 -Inf 或 +Inf,例如 Remainder(a, -Inf) 或 Remainder(b, +Inf),则该函数将返回 a。
  • 如果在该函数中传递 NaN,例如 Remainder(a, NaN),则该函数将返回 NaN。

示例 1:

// Golang program to illustrate
// math.Remainder() Function
package main
  
import (
    "fmt"
    "math"
)
  
// Main function
func main() {
  
    // Finding remainder
    // Using Reminder() function
    res_1 := math.Remainder(36, 5)
    res_2 := math.Remainder(-100, 100)
    res_3 := math.Remainder(45.6, 8.9)
    res_4 := math.Remainder(math.NaN(), 67)
    res_5 := math.Remainder(math.Inf(1), 67)
  
    // Displaying the result
    fmt.Printf("Result 1: %.1f", res_1)
    fmt.Printf("\nResult 2: %.1f", res_2)
    fmt.Printf("\nResult 3: %.1f", res_3)
    fmt.Printf("\nResult 4: %.1f", res_4)
    fmt.Printf("\nResult 5: %.1f", res_5)
  
} 

输出结果:

Result 1: 1.0
Result 2: -0.0
Result 3: 1.1
Result 4: NaN
Result 5: NaN

示例 2:

// Golang program to illustrate
// math.Remainder() Function
package main
  
import (
    "fmt"
    "math"
)
  
// Main function
func main() {
  
    // Finding remainder
    // Using Remainder() function
    nvalue_1 := math.Remainder(49, 6)
    nvalue_2 := math.Remainder(56.7, 3)
  
    // Finding sum of the
    // given remainders
    res := nvalue_1 + nvalue_2
    fmt.Printf("%.2f + %.2f = %.2f",
           nvalue_1, nvalue_2, res)
  
} 

输出结果:

1.00 + -0.30 = 0.70

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程