This is a basic calculator program written in Go. The program starts by declaring three variables: num1
, num2
, and operation
. These variables are used to store the two numbers that the user inputs and the operation (addition, subtraction, multiplication, or division) that the user wants to perform on those numbers.
The program then uses the fmt.Print
and fmt.Scan
functions to prompt the user to enter the two numbers and the operation they want to perform. The fmt.Scan
function reads the user's input and stores it in the corresponding variable.
After the user enters their input, the program uses a switch
statement to check the value of the operation
variable. Depending on the operator, the program performs the corresponding operation and prints the result using fmt.Printf
.
Note: this is a basic calculator program, it does not handle invalid inputs, division by zero, etc. Feel free to expand on this code and add more functionality as needed.
package main
import (
"fmt"
)
func main() {
var num1, num2 int //declaring variables to hold the two numbers
var operation string //declaring variable to hold the operator
fmt.Print("Enter the first number: ") //printing message to user
fmt.Scan(&num1) //reading user input and storing it in num1 variable
fmt.Print("Enter the second number: ")
fmt.Scan(&num2)
fmt.Print("Enter the operation (+, -, *, /): ")
fmt.Scan(&operation) //reading the operator
switch operation { //switch statement to check the operator
case "+":
fmt.Printf("%d + %d = %d\n", num1, num2, num1+num2) //if operator is +, add the numbers and print the result
case "-":
fmt.Printf("%d - %d = %d\n", num1, num2, num1-num2) //if operator is -, subtract the numbers and print the result
case "*":
fmt.Printf("%d * %d = %d\n", num1, num2, num1*num2) //if operator is *, multiply the numbers and print the result
case "/":
fmt.Printf("%d / %d = %f\n", num1, num2, float64(num1)/float64(num2)) //if operator is /, divide the numbers and print the result as float
default:
fmt.Println("Invalid operator") //if operator is not one of the four above, print invalid operator
}
}
Output:
Enter the first number: 2
Enter the second number: 3
Enter the operation (+, -, *, /): +
2 + 3 = 5