shell脚本实现加减乘除计算器

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/chenyixuan0923_yp/article/details/99638117

shell计算器

  1. 使用if语句
#!/bin/bash
# 这是一个计算器
read -t 30 -p "Please input the first number: " num1
read -t 30 -p "Please input the second number: " num2
read -t 30 -p "Please input the second operator(\"+\", \"-\", \"*\", \"/\"): " op
if [ -n "$num1" -a -n "$num2" -a -n "$op" ]
then
    # 1.校验两个操作数必须为数值
    test1=$(echo $num1 | sed 's/[0-9]//g')
    test2=$(echo $num2 | sed 's/[0-9]//g')
    if [ -n "$test1" -o -n "$test2" ]
    then
        echo "Please input number."
        exit 1
    fi
    # 2.判断操作符是否正确
    if [ "$op" == "+" ]
    then
       result=$(($num1 + $num2))
    elif [ "$op" == "-" ]
    then
       result=$(($num1 - $num2))
    elif [ "$op" == "*" ]
    then
       result=$(($num1 * $num2))
    elif [ "$op" == "/" ]
    then
       result=$(($num1 / $num2))
    else
        echo "Please input correct operator, like \"+\", \"-\", \"*\", \"/\"."
        exit 2
    fi
# 3.打印结果
echo "$num1 $op $num2 = $result"
    exit 0
else
    echo "Number and oprator must not be empty"
    exit 3
fi


  
  
    1. 使用case语句
    #!/bin/bash
    # 这是一个计算器
    read -t 30 -p "Please input the first number: " num1
    read -t 30 -p "Please input the second number: " num2
    read -t 30 -p "Please input the second operator(\"+\", \"-\", \"*\", \"/\"): " op
    if [ -n "$num1" -a -n "$num2" -a -n "$op" ]
    then
        # 1.校验两个操作数必须为数值
        test1=$(echo $num1 | sed 's/[0-9]//g')
        test2=$(echo $num2 | sed 's/[0-9]//g')
        if [ -n "$test1" -o -n "$test2" ]
        then
            echo "Please input number."
            exit 1
        fi
    # 2.判断操作符是否正确
        case $op in
            "+")
                result=$(($num1 + $num2))
                ;;
            "-")
                result=$(($num1 - $num2))
                ;;
            "*")
                result=$(($num1 * $num2))
                ;;
            "/")
                result=$(($num1 / $num2))
                ;;
            *)
    echo "Please input correct operator, like \"+\", \"-\", \"*\", \"/\"."
                exit 2
                ;;
        esac
    # 3.打印结果
        echo "$num1 $op $num2 = $result"
        exit 0
    else
        echo "Number and oprator must not be empty"
        exit 3
    fi
    
    
      评论
      添加红包

      请填写红包祝福语或标题

      红包个数最小为10个

      红包金额最低5元

      当前余额3.43前往充值 >
      需支付:10.00
      成就一亿技术人!
      领取后你会自动成为博主和红包主的粉丝 规则
      hope_wisdom
      发出的红包
      实付
      使用余额支付
      点击重新获取
      扫码支付
      钱包余额 0

      抵扣说明:

      1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
      2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

      余额充值