Repository navigation
Expand file tree
/
Copy pathbash_script_3.txt
More file actions
53 lines (43 loc) · 1.56 KB
/
Copy pathbash_script_3.txt
File metadata and controls
53 lines (43 loc) · 1.56 KB
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
Develop an arithmetic calculator that will accept two numbers and calculate the solutions of addition, subtraction, multiplication and division.
Display results to user using 3 decimal places
Use Selection Programming constructs in bash to enhance your program by allowing the user to choose which arithmetic operation they would like to do.
SCRIPT:
#Arithmetic bash script using floating point values
#!/bin/bash
# Print a welcome message and prompt the user to input two numbers
echo "Welcome to the arithmetic calculator!"
read -p "Enter the first number: " num1
read -p "Enter the second number: " num2
# Prompt the user to choose an arithmetic operation
echo "Choose an option:"
echo "1. Addition (+)"
echo "2. Subtraction (-)"
echo "3. Multiplication (*)"
echo "4. Division (/)"
read -p "Enter the operation number: " op
# Use a case statement to perform the corresponding arithmetic operation
case $op in
1)
result=$(echo "scale=3; $num1 + $num2" | bc) # Addition
echo "The sum of $num1 and $num2 is: $result"
;;
2)
result=$(echo "scale=3; $num1 - $num2" | bc) # Subtraction
echo "The difference between $num1 and $num2 is: $result"
;;
3)
result=$(echo "scale=3; $num1 * $num2" | bc) # Multiplication
echo "The product of $num1 and $num2 is: $result"
;;
4)
if [[ $num2 -eq 0 ]]; then
echo "Division by zero is undefined"
else
result=$(echo "scale=3; $num1 / $num2" | bc) # Division
echo "The quotient of $num1 divided by $num2 is: $result"
fi
;;
*)
echo "Invalid input" # If the user enters an invalid operation number
;;
esac