NWJ619
2022-07-06 06:28
采纳率: 66.7%
浏览 323

用unix模拟一个简单的计算器

用unix模拟一个简单的计算器,包括(+,-,x,/)和(MS, M+,MC, MR,X)功能。

while true
do
echo " Enter the operand1"
read operand1

echo " Enter the operator"
read operator
echo " Enter the operand2"
read operand2
if [ "operand1" == "$result" ]
then
echo "operand1 is: $result"
echo ""
fi

   if [ "$operator" == "+" ]
     then
       result=$(($operand1 + $operand2))

   elif [ "$operator" == "-" ]
    then
       result=$(($operand1 - $operand2))

   elif [ "$operator" == "x" ]
     then
       result=$(($operand1 x $operand2))

   elif [ "$operator" == "/" ]
     then
        if [ $operand2 -eq 0]
           then
             echo "Can't divide by zero. please re-enter divisor."
        else
            result=$(($operand1 / $operand2))
        fi

   elif [ "$operator" == "X" ]
       then
        exit
   elif [ "$operator" == "MS" ]
       then
         MS -> $result

   elif [ "$operator" == "MR" ]
       then
         operand2=$result
         MR -> $operand2

   elif [ "$operator" == "M+" ]
       then
         M+ -> $((result+MS))

   elif [ "$operator" == "MC" ]
       then
         $result=0
         MC -> 0
   else
       echo "Sorry, is not a valid operator. plrase re-enter operator. "
   fi

echo "$operand1 $operator $operand2 = $result"
done

只能计算(+,-, x , /),并且当数值不符合条件时不能做到重复,而且(MS, M+,MC, MR,X)功能并不能使用。
运用 while loop和if,只限一个小时内解决
可以模拟成正常我们日常生活中的计算器

$ ./calc
[ user instruction displayed ]
Enter operand: 3
Enter operator: +
Enter operand: 4
3 + 4 = 7
Enter operator: -
enter operand: 12
7 - 12 = -5
Enter operator: MS
-5 -> M
Enter operator: x
enter operand: 3
-5 x 3 = -15
Enter operator: C
results cleared(清除结果)
enter operand: MR
M -> -5
Enter operator: x
enter operand: MR
M -> -5
-5 x -5 = 25
Enter operator: M+
25 + -5 = 20 -> M
Enter operator: /
enter operand: 0
can't divide by zero. plesae re-enter divisor.(不能除以0,请重新输入)
enter operand: 0
can't divide by zero. plesae re-enter divisor.(不能除以0,请重新输入)
enter operand: -6
25 / -6 = -4
Enter operator: +
enter operand: C
results cleared(清除结果)
enter operand: -9
Enter operator: K
Sorry, k, is not a valid operator.please re-enter the operator. (k不是一个有效的operator,请重新输入)
Enter operator: Q
Sorry, Q, is not a valid operator.please re-enter the operator. (Q 不是一个有效的operator,请重新输入)
Enter operator: MC
0 -> M
Enter operator: +
enter operand:3
-9 + 3 = -6
Enter operator: X
Good bye.(再见)

2条回答 默认 最新

相关推荐 更多相似问题