输入两个数字,输入“a”时相加,输入“s”时相减

输入两个数字,输入“a”时相加,输入“s”时相减

所以我在这段代码上遇到了一些麻烦。当我尝试执行时,我收到消息行 12: 0: command not found


#!/bin/bash

let results=0;

echo "First number please"

read num1

echo "Second mumber"

read num2

echo "Enter operation a=add, s=subtract, m=multiply, and d=divide"

read Op

if [ "$Op" = "a" ]

then

results=$((num1+num2))

elif [ "$Op" = "s" ]

then

results=$((num1-num2))

elif [ "$Op" = "d" ]

then

results=$((num1/num2))

elif [ "$Op" = "m" ]

then

results=$((num1*num2))

fi

答案1

elif 与最后一个 else 一样不是有效关键字。使用:

If *condition 1*
    #Do Something
elif *condition 2*
    #Do Something Else
else
    #Do this as a last resort
fi

当不像 bc 答案中那样转换为字符串时,Else If 需要 else。

参考:4 Bash If 语句示例(If then fi、If then else fi、If elif else fi、嵌套 if )

答案2

我将你的 shell 脚本更改为以下代码并且它可以工作,无论如何除以零的错误仍然存​​在:

#!/bin/bash

let results=0;
echo "First number please"
read num1
echo "Second number"
read num2
echo "Enter operation a=add, s=subtract, m=multiply, and d=divide"
read Op
if [ "$Op" = "a" ] ; then
    results=`echo "$num1+$num2" |bc `
elif [ "$Op" = "s" ]; then 
    results=`echo "$num1-$num2" |bc `
elif [ "$Op" = "d" ]; then 
    results=`"$num1/$num2" |echo bc`
elif [ "$Op" = "m" ] ; then 
    results=`echo "$num1*$num2"|bc`
else 
    echo "Enter operation a=add, s=subtract, m=multiply, and d=divide"
    read Op
fi;
echo $results

答案3

我已经完成了。我必须删除它,|bc因为由于某种原因它与我使用的终端不兼容。我必须将结果行采用这种格式,$(($num1+$num2))因为它没有给我答案。它之前所做的只是显示输入,而不是算术结果。最终代码如下:

let results=0;
echo "First number please"
read num1 
echo "Second mumber"
read num2
echo "Enter operation a=add, s=subtract, m=multiply, and d=divide"
read Op
if [ "$Op" = "a" ] ; then
    results="$(($num1+$num2))" 
elif [ "$Op" = "s" ]; then
    results="$(($num1-$num2))"
elif [ "$Op" = "d" ]; then
    results="$(($num1/$num2))"
elif [ "$Op" = "m" ] ; then
    results="$(($num1*$num2))"
else
    echo "Enter operation a=add, s=subtract, m=multiply, and d=divide"
    read Op
fi;
echo "$results"

相关内容