{

Golang example - program to multiply two numbers


Golang map examples

In this blog post, Learn the below things in go language.

  • Multiply two integers
  • Multiply two floating numbers
  • Multiple integers and floating numbers

Example program to Multiply two integers

In this example.

  • Declared two variables of type integer
  • Assign them with values using equal operator(=)
  • Multiple two integers using multiply operator and the result is assigned to an integer variable.
  • Finally, Print the result using %d in the Printf function.
package main

import (
    "fmt"
)

func main() {
    var number1, number2 int
    number1 = 5
    number2 = 6
    result: = number1 * number2
    fmt.Printf("Multiply result is  %d\n", result)

}

Output:

Multiply result is  30  

golang Example program to Multiply two floating numbers

In this program.

  • Declared two variables of type float
  • Assign float values using equal operator(=)
  • Multiple two floats using multiply operator and the result is assigned to a third float variable.
  • Finally, Print the result using %f for float in the Printf function.
package main

import (
    "fmt"
)

func main() {
    var number1, number2 float64
    number1 = 5.1
    number2 = 6.3
    result: = number1 * number2
    fmt.Printf("Multiply floating numbers result is  %f\n", result)

}

Output:

Multiply floating numbers result is  32.130000  

Example program to Multiply integer and floating numbers

When you are doing multiply with different types (int and float), you got error invalid operation: number1 * number2 (mismatched types int and float64). The following program gives an error.

package main

import (
    "fmt"
)

func main() {
    var number1 int
    var number2 float64
    number1 = 5
    number2 = 6.3
    result: = number1 * number2
    fmt.Printf("Multiply float and int numbers result is  %f\n", result)

}

Output:

# command-line-arguments  
Test.go:12:20: invalid operation: number1 * number2 (mismatched types int and float64)  

Importantly,

The number must be float when multiplied with the float number. So, the int type need to convert to float using float64(intvalue)
Here is a working code

package main

import (
    "fmt"
)

func main() {
    var number1 int
    var number2 float64
    number1 = 5
    number2 = 6.3
    result: = float64(number1) * number2
    fmt.Printf("Multiply float and int numbers result is  %f\n", result)

}

Output:

Multiply float and int numbers result is  31.500000  

Conclusion

In this tutorial, Learne the multiplication of numbers and integers in golang

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.