我创建了一个充当简单计算器的bash脚本。计算器的目标是不断询问用户输入。此输入包括操作和两个数字。
但是,我遇到了一个问题,即在提交第一个操作后,while
循环将继续执行该初始操作。
代码:
#!/bin/bash
echo "Calculator"
echo "Input an Operation: +, -, *, /, and % (0 to stop): "
read OP
while [ $OP != "0" ]
do
if [ $OP == "+" ]; then
echo "Add Numbers"
SUM=0
echo "Enter number1: "
read N1
echo "Enter number2: "
read N2
SUM=$((N1+N2))
echo "Result: $SUM"
elif [ $OP == "-" ]; then
echo "Subtract Numbers"
SUB=0
echo "Enter number1: "
read N1
echo "Enter number2: "
read N2
SUB=$((N1-N2))
echo "Result: $SUB"
elif [ $OP == "*" ]; then
echo "Multiple Numbers"
MUL=0
echo "Enter number1: "
read N1
echo "Enter number2: "
read N2
MUL=$((N1*N2))
echo "Result: $MUL"
elif [ $OP == "/" ]; then
echo "Divide Numbers"
DIV=0
echo "Enter number1: "
read N1
echo "Enter number2: "
read N2
DIV=$((N1/N2))
echo "Result: $DIV"
elif [ $OP == "%" ]; then
echo "Modulus Numbers"
SUB=0
echo "Enter number1: "
read N1
echo "Enter number2: "
read N2
MOD=$((N1%N2))
echo "Result: $MOD"
fi
done
exit 0
我知道这是一个很小但却无法弄清楚我在这里缺少的东西。
答案 0 :(得分:0)
将初始提示放在循环中。
而不是:
echo "Input an Operation: +, -, *, /, and % (0 to stop): "
read OP
while [ $OP != "0" ]
do
...
这样做:
while [ $OP != "0" ]
do
echo "Input an Operation: +, -, *, /, and % (0 to stop): "
read OP
...