The smallest command-line program reads a command and its numbers.
What to build
A calculator that runs commands such as add 2 3.
Requirements
- Read n, then n lines
COMMAND A Bwith whole numbers A and B. add,sub,mulanddivprintresult: R. Fordivuse whole-number division; when B is 0 printerror: division by zero.- For any other command print
unknown command: NAME.
Input
Line 1: n. Then n lines.
Output
One line per command.
Constraints
1 ≤ n ≤ 50; A and B are between -10000 and 10000.
Example
Input:
4
add 2 3
sub 2 3
mul 4 5
div 7 2
Output:
result: 5
result: -1
result: 20
result: 3
Why it works
A switch on the command word picks the code to run and default handles anything unknown. The check for zero comes before the division so the program never stops.
Examples
Example 1 · Input
4 add 2 3 sub 2 3 mul 4 5 div 7 2
Expected output
result: 5 result: -1 result: 20 result: 3
Example 2 · Input
3 div 5 0 pow 2 3 div -7 2
Expected output
error: division by zero unknown command: pow result: -3
Hints
Hint 1
Read the first number n, then use a loop with fmt.Scan(&cmd, &a, &b).
Hint 2
Use a switch on cmd with cases add, sub, mul and div, and a default case.
Solution
Show one correct solution (try it yourself first)
package main
import "fmt"
func main() {
var n int
fmt.Scan(&n)
for i := 0; i < n; i++ {
var cmd string
var a, b int
fmt.Scan(&cmd, &a, &b)
switch cmd {
case "add":
fmt.Println("result:", a+b)
case "sub":
fmt.Println("result:", a-b)
case "mul":
fmt.Println("result:", a*b)
case "div":
if b == 0 {
fmt.Println("error: division by zero")
} else {
fmt.Println("result:", a/b)
}
default:
fmt.Println("unknown command:", cmd)
}
}
}