How to multiply two numbers in Golang | Go by Examples
- Admin
- Dec 31, 2023
- Golang-examples
In this blog post, Learn the below things in the go language.
- Multiply two integers
- Multiply two floating numbers
- Multiple integers and floating numbers
How to Multiply two integers in Golang with example
In this example.
- Declared two variables of type integer
- Assign them with values using the equal operator(=)
- Multiply 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 the 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 thePrintf
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 multiplying with different types (int
and float
), you got the 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 needs 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, Learned the multiplication of numbers and integers in golang