刚学shell脚本写了个小 计算器,加减除都可以,乘法不行,哪儿错了
#!/bin/bashecho"firstnumber"readaecho"fangfa"readfangfaecho"secondnumber"readbif[$fan...
#!/bin/bash
echo "first number"
read a
echo "fangfa"
read fangfa
echo "second number"
read b
if [ $fangfa = "+" ];then
echo $(($a+$b))
elif [ $fangfa = "-" ];then
echo $(($a-$b))
elif [ $fangfa = " \* " ];then
echo $(($a*$b))
else
echo $(($a/$b))
fi 展开
echo "first number"
read a
echo "fangfa"
read fangfa
echo "second number"
read b
if [ $fangfa = "+" ];then
echo $(($a+$b))
elif [ $fangfa = "-" ];then
echo $(($a-$b))
elif [ $fangfa = " \* " ];then
echo $(($a*$b))
else
echo $(($a/$b))
fi 展开
展开全部
你的问题在:elif [ $fangfa = " \* " ]; 这句并不能判断到“*“乘号;
正确的结果如下:
#!/bin/bash
echo "first number"
read a
echo "fangfa"
read fangfa
echo "second number"
read b
if [ "$fangfa" = "+" ];then
echo $(($a+$b))
elif [ "$fangfa" = "-" ];then
echo $(($a-$b))
elif [ "$fangfa" = "*" ];then
echo $(($a*$b))
elif [ "$fangfa" = "/" ];then
echo $(($a/$b))
fi
===============================================
脚本优化版本:
#!/bin/bash
read -p "input first number: " num1
read -p "input operator: " operator
read -p "input second number: " num2
if [ "$operator" == "+" ];then
echo " num1 + num2 = $(($num1+$num2))"
elif [ "$operator" == "-" ];then
echo "num1 - num2 = $(($num1-$num2))"
elif [ "$operator" == "*" ];then
echo "num1 * num2 = $(($num1*$num2))"
elif [ "$operator" == "/" ];then
echo "num1 / num2 = $(($num1/$num2))"
fi
正确的结果如下:
#!/bin/bash
echo "first number"
read a
echo "fangfa"
read fangfa
echo "second number"
read b
if [ "$fangfa" = "+" ];then
echo $(($a+$b))
elif [ "$fangfa" = "-" ];then
echo $(($a-$b))
elif [ "$fangfa" = "*" ];then
echo $(($a*$b))
elif [ "$fangfa" = "/" ];then
echo $(($a/$b))
fi
===============================================
脚本优化版本:
#!/bin/bash
read -p "input first number: " num1
read -p "input operator: " operator
read -p "input second number: " num2
if [ "$operator" == "+" ];then
echo " num1 + num2 = $(($num1+$num2))"
elif [ "$operator" == "-" ];then
echo "num1 - num2 = $(($num1-$num2))"
elif [ "$operator" == "*" ];then
echo "num1 * num2 = $(($num1*$num2))"
elif [ "$operator" == "/" ];then
echo "num1 / num2 = $(($num1/$num2))"
fi
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询