1
0
Fork 0
pr3-ws202627/go/01-basics/calculator.go

137 lines
2.4 KiB
Go

package main
import (
"fmt"
)
func main() {
const (
add = "add"
subtract = "subtract"
multiply = "multiply"
divide = "divide"
exit = "exit"
)
//TODO: implement according to README.md
fmt.Println("Welcome to the Simple Calculator!")
for {
var operation string
fmt.Print("\nEnter operation (add, subtract, multiply, divide, exit): ")
fmt.Scan(&operation)
//the following code just demonstrates how to use fmt.Scan
if operation == exit {
fmt.Println("Goodbye!")
break
}
var str string
fmt.Print("Please enter a string: ")
fmt.Scan(&str)
var num1, num2 float64
fmt.Print("Enter the first number: ")
fmt.Scan(&num1)
fmt.Print("Enter the second number: ")
fmt.Scan(&num2)
var x float64
fmt.Print("Please enter a float: ")
fmt.Scan(&x)
fmt.Printf("You entered '%s' and %f\n", str, x)
switch operation {
case add:
fmt.Printf("Result: %.2f\n", num1+num2)
case subtract:
fmt.Printf("Result: %.2f\n", num1-num2)
case multiply:
fmt.Printf("Result: %.2f\n", num1*num2)
case divide:
if num2 == 0 {
fmt.Println("Error: Division by zero is not allowed!")
} else {
fmt.Printf("Result: %.2f\n", num1/num2)
}
default:
fmt.Println("Invalid operation. Please try again.")
}
}
}
package main
import (
"fmt"
)
const (
opAdd = "add"
opSubtract = "subtract"
opMultiply = "multiply"
opDivide = "divide"
opExit = "exit"
)
var result float64
func add(a, b float64) {
result = a + b
}
func multiply(a, b float64) {
result = a * b
}
func subtract(a, b float64) {
result = a - b
}
func divide(a, b float64) {
result = a / b
}
func main() {
var x float64
var y float64
//TODO: implement according to README.md
//the following code just demonstrates how to use fmt.Scan
for {
fmt.Print("What would you like to do? (add|subtract|divide|multiply|exit)")
var str string
fmt.Scan(&str)
if str == opExit {
break
} else {
fmt.Print("Please enter a float: ")
fmt.Scan(&x)
fmt.Print("Please enter a float: ")
fmt.Scan(&y)
switch str {
case opAdd:
add(x, y)
fmt.Println(result)
case opMultiply:
multiply(x, y)
fmt.Println(result)
case opDivide:
if y == 0 {
fmt.Println("Division by 0 is not possible")
continue
}
divide(x, y)
fmt.Println(result)
case opSubtract:
subtract(x, y)
fmt.Println(result)
default:
fmt.Println("Unknown operation")
}
}
}
}