第三章:Creating Utilities--24.一个交互式的计算器

   之前写了第九个脚本,允许命令行调用bc进行浮点计算,所以现在必然要写一个交互式的,基于命令行的计算器封装脚本。它有一个优点:即使加上帮助信息,也很短。

代码:

 1 #!/bin/sh
 2 
 3 # calc.sh -- 一个看起来像是bc的前端的命令行计算器
 4 
 5 scale=2
 6 
 7 show_help()
 8 {
 9     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循环了。它创建一个calc>的提示,直到用户完成输入。当然,这个脚本的间接性成就了它自己:shell脚本并不需要特别的复杂。

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

运行结果:

 1 calc 150 / 3.5 
 2 42.85 
 3 
 4 ./calc.sh 
 5 Calc - a simple calculator. Enter 'help' for help, 'quit' to quit.
 6 calc> help
 7 In addition to standard math function, calc also supports
 8 
 9    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 

 

转载于:https://www.cnblogs.com/lalala23456/archive/2013/01/04/2843843.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值