Golang example - program to multiply two numbers


 In this blog post, you are going to learn below things

  • Multiply two integers 
  • Multiply two floating numbers
  • Multiply integer and floating numbers 

Example1 program to Multiply two integers

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 is

Multiply result is  30  

Example2 program to Multiply two floating numbers

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 is

Multiply floating numbers result is  32.130000  

Example2 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 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 is

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

When you are multiply with float, The other number must be float. So 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 is

Multiply float and int numbers result is  31.500000  

Similar Posts