Linux 스크립트에서 계산기를 만드는 방법은 무엇입니까?

Linux 스크립트에서 계산기를 만드는 방법은 무엇입니까?

계산기를 만들려고 합니다.

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))`

관련 정보