Open In App

Finding Maximum of Two Numbers in Golang

Last Updated : 21 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. You can find the largest number among the given two numbers with the help of Max() function provided by the math package. So, you need to add a math package in your program with the help of the import keyword to access the Max() function.
Syntax: 
 

func Max(a, b float64) float64

 

  • If you pass +Inf in this function like Max(+Inf, b) or Max(a, +Inf), then this function will return +Inf.
  • If you pass NaN in this function like Max(NaN, b) or Max(a, NaN), then this function will return NaN.
  • If you pass -0 in this function like Max(-0, -0), then this function will return -0.
  • If you pass -0 or +0 in this function like Max(+0, -0) or Max(+0, +0) or Max(-0, +0) or Max(+0, +0), then this function will return +0.

Example 1:
 

Go




// Golang program to illustrate
// how to find the largest number
 
package main
 
import (
    "fmt"
    "math"
)
 
// Main function
func main() {
 
    // Finding largest number
    // among the given numbers
    // Using Max() function
    res_1 := math.Max(0, -0)
    res_2 := math.Max(-100, 100)
    res_3 := math.Max(45.6, 8.9)
    res_4 := math.Max(math.NaN(), 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)
 
}


Output:
 

Result 1: 0.0
Result 2: 100.0
Result 3: 45.6
Result 4: NaN

Example 2:
 

Go




// Golang program to illustrate
// how to find the largest number
 
package main
 
import (
    "fmt"
    "math"
)
 
// Main function
func main() {
 
    // Finding largest number
    // among the given numbers
    // Using Max() function
    nvalue_1 := math.Max(34, 67)
    nvalue_2 := math.Max(56.7, 90.8)
 
    // Adding maximum numbers
    res := nvalue_1 + nvalue_2
    fmt.Printf("%.2f + %.2f = %.2f",
            nvalue_1, nvalue_2, res)
 
}


Output: 
 

67.00 + 90.80 = 157.80

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads