-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshell-calculator
97 lines (86 loc) · 2.27 KB
/
shell-calculator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/bin/bash
# You can add a prompt at the end of the calculator function to ask the user if they want to repeat the operation.
# Function to perform addition
addition() {
echo "$1 + $2" | bc
}
# Function to perform subtraction
subtraction() {
echo "$1 - $2" | bc
}
# Function to perform multiplication
multiplication() {
echo "$1 * $2" | bc
}
# Function to perform division
division() {
if [ "$2" -ne 0 ]; then
echo "scale=2; $1 / $2" | bc
else
echo "Error: Division by zero is undefined."
fi
}
# Function to perform modulus
modulus() {
if [ "$2" -ne 0 ]; then
echo "$1 % $2" | bc
else
echo "Error: Modulus by zero is undefined."
fi
}
# Main calculator function
calculator() {
echo "Calculator Menu:"
echo "1. Addition"
echo "2. Subtraction"
echo "3. Multiplication"
echo "4. Division"
echo "5. Modulus"
echo "6. Exit"
read -p "Enter your choice (1-6): " choice
case $choice in
1)
read -p "Enter the first number: " num1
read -p "Enter the second number: " num2
result=$(addition "$num1" "$num2")
echo "Result: $result"
;;
2)
read -p "Enter the first number: " num1
read -p "Enter the second number: " num2
result=$(subtraction "$num1" "$num2")
echo "Result: $result"
;;
3)
read -p "Enter the first number: " num1
read -p "Enter the second number: " num2
result=$(multiplication "$num1" "$num2")
echo "Result: $result"
;;
4)
read -p "Enter the numerator: " num1
read -p "Enter the denominator: " num2
result=$(division "$num1" "$num2")
echo "Result: $result"
;;
5)
read -p "Enter the dividend: " num1
read -p "Enter the divisor: " num2
result=$(modulus "$num1" "$num2")
echo "Result: $result"
;;
6)
echo "Exiting the calculator. Goodbye!"
exit 0
;;
*)
echo "Invalid choice. Please enter a number between 1 and 6."
;;
esac
# Recursive call for continuous operation
calculator
}
# Start the calculator
calculator
```
I added a new function `modulus` for the modulus operation, and I included it in the menu. Users can choose option '5' to perform the modulus operation. The script continues to run until the user chooses to exit by entering '6'.