我正在尝试创建一个计算器:
echo "What is your number?"
read n1
echo "what is your second number?"
read n2
echo "what do you want to do?"
echo "1. add"
echo "2. subtract"
echo "3. divide"
echo "4. multiply"
read ans
if
ans=$(( $n1+$n2 )); then
echo $ans
elif
ans=$(( $n1-$n2 )); then
echo $ans
elif
ans=$(( $n1/$n2 )); then
echo $ans
elif
ans=$(( $n1*$n2 )); then
echo $ans
else
但是当我插入字母时它显示0。我该如何改进它?有时它也会给我错误的答案。
答案1
尝试使用while loop
:
input="yes"
while [[ $input = "yes" ]]
do
PS3="Press 1 for Addition, 2 for subtraction, 3 for multiplication and 4 for division: "
select math in Addition Subtraction Multiplication Division
do
case "$math" in
Addition)
echo "Enter first no:"
read num1
echo "Enter second no:"
read num2
result=`expr $num1 + $num2`
echo Answer: $result
break
;;
Subtraction)
echo "Enter first no:"
read num1
echo "Enter second no:"
read num2
result=`expr $num1 - $num2`
echo Answer: $result
break
;;
Multiplication)
echo "Enter first no:"
read num1
echo "Enter second no:"
read num2
result=`expr $num1 * $num2`
echo Answer: $result
break
;;
Division)
echo "Enter first no:"
read num1
echo "Enter second no:"
read num2
result=$(expr "scale=2; $num1/$num2" | bc)
echo Answer = $result
break
;;
*)
echo Choose 1 to 4 only!!!!
break
;;
esac
done
done
答案2
clear
sum=0
i="y"
echo " Enter one no."
read n1
echo "Enter second no."
read n2
while[ $i = "y" ]
do
echo "1.Addition"
echo "2.Subtraction"
echo "3.Multiplication"
echo "4.Division"
echo "Enter your choice"
read ch
case $ch in
1)sum=`expr $n1 + $n2`
echo "Sum ="$sum;;
2)sum=`expr $n1 - $n2`
echo "Sub = "$sum;;
3)sum=`expr $n1 \* $n2`
echo "Mul = "$sum;;
4)sum=`expr $n1 / $n2`
echo "Div = "$sum;;
*)echo "Invalid choice";;
esac
echo "Do u want to continue ?"
read i
if [ $i != "y" ] then
exit
fi
done
答案3
试试这个更简单的。
#!/bin/bash
echo "enter first number"
read p
echo "enter second number"
read q
echo "enter the operator"
read r
sum=`expr $p "$r" $q`
echo "the total" $sum
答案4
echo "Enter Your Choise : "
echo "1.Addition"
echo "2.Substtaction"
echo "3.Multiplication"
echo "4.Division"
read opr
echo "Enter first Number : "
read n1
echo "Enter second Number : "
read n2
if [$opr=1] then
echo `expr ans=$((n1+n2))`
elif [$opr=2] then
echo `expr ans=$((n1-n2))`
elif [$opr=3] then
echo `expr ans=$((n1*n2))`
else [$opr=4] then
echo `expr ans=$((n1/n2))`