交互式计算器脚本 -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

   

    01

    #!/bin/sh

    02

    03

    # calc.sh -- 一个看起来像是bc的前端的命令行计算器

    04

    05

    scale=2

    06

    07

    show_help()

    08

    {

    09

    cat << EOF

    10

    In addition to standard math function, calc also supports

    11

    12

    a % b  remainder of a/b

    13

    a ^ b  exponential: a raised to the b power

    14

    s(x)  sine of x, x in radians

    15

    c(x)  cosine of x, x in radians

    16

    a(x)  actangent of x, returns radians

    17

    l(x)  natural log of x

    18

    e(x)  exponential log of raising e to the x

    19

    j(n, x) bessel function of integer order n of x

    20

    scale N show N fractional digits(default = 2)

    21

    22

    EOF

    23

    }

    24

    25

    if [ $# -gt 0 ]; then

    26

    exec scriptbc.sh "$@"

    27

    fi

    28

    29

    echo "Calc - a simple calculator. Enter 'help' for help, 'quit' to quit."

    30

    31

    echo -n "calc> "

    32

    33

    while read command args  # 像不像Python的顺序解包

    34

    do

    35

    case $command in

    36

    quit|exit) exit 0;;

    37

    help|\?) show_help;;

    38

    scale)  scale=$args;;

    39

    *)    scriptbc.sh -p $scale "$command" "$args";;

    40

    esac

    41

    42

    echo -n "calc> "

    43

    done

    44

    45

    echo ""

    46

    47

    exit 0

    脚本如何运行:

    可能这个脚本最有意思的部分就是那个while循环了,

交互式计算器脚本

电脑资料

交互式计算器脚本》(https://www.unjs.com)。它创建一个calc>的提示,直到用户完成输入。当然,这个脚本的间接性成就了它自己:shell脚本并不需要特别的复杂。

    运行脚本:

    这个脚本跑起来非常简单,因为它是一个交互式的,可以提示用户完成特定操作。如果有参数传递给它,它就转而把这些参数传给scripbc.sh。

    运行结果:

    01

    calc 150 / 3.5

    02

    42.85

    03

    04

    ./calc.sh

    05

    Calc - a simple calculator. Enter 'help' for help, 'quit' to quit.

    06

    calc> help

    07

    In addition to standard math function, calc also supports

    08

    09

    a % b  remainder of a/b

    10

    a ^ b  exponential: a raised to the b power

    11

    s(x)  sine of x, x in radians

    12

    c(x)  cosine of x, x in radians

    13

    a(x)  actangent of x, returns radians

    14

    l(x)  natural log of x

    15

    e(x)  exponential log of raising e to the x

    16

    j(n, x) bessel function of integer order n of x

    17

    scale N show N fractional digits(default = 2)

    18

    19

    calc> 54354 ^ 3

    20

    160581137553864

    21

    22

    calc> quit

最新文章