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

Linux 专栏收录该内容
4 篇文章 0 订阅

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

  • 12
    点赞
  • 3
    评论
  • 29
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值