Use and complete the template provided. The entire template must be completed. If you don't, your post may be deleted!
The problem statement, all variables and given/known data:
Create a calculator application in your home folder called itncacl that will perform the following applications:
Add two numbers
Subtract two numbers
Multiply two numbers
Divide two numbers
You cannot divide by zero, so create a condition that checks for and prevents a that condition.
Relevant commands, code, scripts, algorithms:
The attempts at a solution (include all code and scripts):
#!/bin/bash
clear
echo "Enter the first number:"
read n1
echo "Choose an operation:"
echo "1. add"
echo "2. subtract"
echo "3. multiply"
echo "4. divide"
read opr
echo "Enter the second number:"
read n2
if [ $opr = "1" ]
then
echo $((n1+n2))
elif [ $opr = "2" ]
then
echo $((n1-n2))
elif [ $opr = "3" ]
then
echo $((n1*n2))
elif [ $opr = "4" ]
then
echo $((n1/n2))
fi
exit 0
My only question is how do I add to my code so that when I try to divide by zero it will show Cannot divide by zero or invalid? Thanks!
Complete Name of School (University), City (State), Country, Name of Professor, and Course Number (Link to Course):
Northern Virginia Comm College, VA, USA, Saleh, ITN171
Note: Without school/professor/course information, you will be banned if you post here! You must complete the entire template (not just parts of it).
I would think the simplest way to handle this would be to add an additional condition inside your pre-existing condition (that is not related to Obama Care :)) to test if "n2" is 0 (zero) before you attempt to divide by it:
elif [ $opr = "4" ]
then
... test if n2 is zero, if not, do this...
echo $((n1/n2))
... else do this
fi
e.g.
...
elif [ $opr = "4" ]
then
if [ "$n2" != 0 ]; then # for numbers, normally, you would use "-ne" (not equal to) in place of "!=", but you didn't sanitise the input
echo $((n1/n2))
else
echo "Divide by zero"
fi
fi
...
If the intention is not to show that you are dividing by zero, but to prevent it doing so altogether, you can amend the existing elif that handles that case to also check that "n2" is not zero. Talking of which, it may be better (simpler) to use a "case" statement instead of "if" - ifs can get a bit clumsy looking, when there's lots of elifs going on.
Sorry, I don't quite understand the point here. In your posting, you wrote: My only question is how do I add to my code so that when I try to divide by zero it will show Cannot divide by zero or invalid? I don't see how this relates to record extraction.
If you have questions about other subjects, please create separate posts.