【发布时间】:2021-05-24 21:24:41
【问题描述】:
#!/bin/bash
while true
do
if [[ $# -eq 0 ]] ; then
result=$((operand1+operand2))
result=$((operand1-operand2))
result=$((operand1*operand2))
if [[ $result ]] ; then
operand1=$result
echo "operand 1 is: $result"
echo ""
else
echo Enter operand1 value:
read operand1
fi
# Offer choices
echo 1. Addition
echo 2. Subtraction
echo 3. Multiplication
echo 4. Division
echo 5. Exit
echo Enter your choice:
read choice
if [[ $choice != 1 && $choice != 2 && $choice != 3 && $choice != 4 && $choice != 5 ]] ; then
echo Sorry not a valid operator - please try again
echo Enter your choice:
read choice
fi
echo Enter operand2 value:
read operand2
# get operands and start computing based on the user's choice
if [[ $choice -eq 1 ]] ; then
echo ----------------------------------------
echo Addition of $operand1 and $operand2 is $((operand1+operand2))
echo ----------------------------------------
echo
elif [[ $choice -eq 2 ]] ; then
echo ----------------------------------------
echo Subtraction of $operand1 and $operand2 is $((operand1-operand2))
echo ----------------------------------------
echo
elif [[ $choice -eq 3 ]] ; then
echo ----------------------------------------
echo Multiplication of $operand1 and $operand2 is $((operand1*operand2))
echo ----------------------------------------
echo
elif [[ $choice -eq 4 && operand2 -eq 0 ]] ; then
echo Can not divide by 0 please try again
echo Please enter operand2
read operand2
echo ----------------------------------------
echo Division of $operand1 and $operand2 is $((operand1/operand2))
echo ----------------------------------------
echo
elif [[ $choice -eq 4 && operand2 -ne 0 ]] ; then
echo ----------------------------------------
echo Division of $operand1 and $operand2 is $((operand1/operand2))
echo ----------------------------------------
echo
elif [[ $choice -eq 5 ]] ; then
exit
else
echo ----------------------------------------
echo Invalid choice.. Please try again
echo ----------------------------------------
echo
fi
else
echo ----------------------------------------
echo You either passed too many parameters or too less
echo than the optimum requirement.
echo
echo This program accepts a maximum of 2 arguments or no
echo argument at all in order to run successfully.
echo ----------------------------------------
fi
done
我正在专门研究这段代码的顶部。我正在尝试使用它,以便用户的结果将用于下一个操作数 1。每次计算后我得到操作数 1 = 0。知道如何解决这个问题吗? 操作数 1 是:0
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice:
1
Enter operand2 value:
1
----------------------------------------
Addition of 0 and 1 is 1
----------------------------------------
operand 1 is: 0
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter your choice:
【问题讨论】:
-
你试过用 bash -x 运行代码吗?
-
您能否编辑您的问题以显示显示错误的示例运行?
-
@MarkPlotnick,奇怪的是,当我清除并在我的 shell 中重新输入代码时它可以工作,然后计算我清除之前的所有先前值并添加它们,尽管当我开始时这是我的操作数 1做。添加到问题
-
循环体开头的
result的3 个赋值的目的是什么?没有分配给result取决于所选操作。 -
您能解释一下
if [[ $result ]]的用途吗?我认为可能有更好的方法。