Linux算术运算

let方法:

[student@myhost ~]$ a=1
[student@myhost ~]$ b=3
[student@myhost ~]$ let c=a+b       #c前不用加$
[student@myhost ~]$ echo $c
4

[student@myhost ~]$ let a++
[student@myhost ~]$ echo $a
2

[student@myhost ~]$ let a+=3
[student@myhost ~]$ echo $a
5

[ ]方法:

[student@myhost ~]$ echo $a
2
[student@myhost ~]$ echo $b
3
[student@myhost ~]$ c=$[a+b]
[student@myhost ~]$ echo $c
5
[student@myhost ~]$ c=$[a+3]
[student@myhost ~]$ echo $c
5
[student@myhost ~]$ c=$[$a+3]
[student@myhost ~]$ echo $c
5

(( ))方法:

[student@myhost ~]$ echo $a
2
[student@myhost ~]$ echo $b
3
[student@myhost ~]$ c=$((a+b))
[student@myhost ~]$ echo $c
5
[student@myhost ~]$ c=$((a+3))
[student@myhost ~]$ echo $c
5
[student@myhost ~]$ c=$(($a+3))
[student@myhost ~]$ echo $c
5

expr方法:

[student@myhost ~]$ echo $a
2
[student@myhost ~]$ echo $b
3

[student@myhost ~]$ c=`expr 1+2`
[student@myhost ~]$ echo $c
1+2
[student@myhost ~]$ c=`expr 1 + 2`
[student@myhost ~]$ echo $c
3

[student@myhost ~]$ c=`expr $a + $b`
[student@myhost ~]$ echo $c
5

[student@myhost ~]$ c=$(expr $a+$b)
[student@myhost ~]$ echo $c
2+3
[student@myhost ~]$ c=(expr $a + $b)
[student@myhost ~]$ echo $c
expr
[student@myhost ~]$ c=$(expr $a + $b)
[student@myhost ~]$ echo $c
5

以上方法仅支持整数运算。
bc方法(支持浮点数):

[student@myhost ~]$ echo "5*1.3"|bc
6.5
[student@myhost ~]$ a=4
[student@myhost ~]$ echo "$a*1.5"|bc
6.0

[student@myhost ~]$ echo "scale=2;3/8"|bc    #scale规定小数位,用分号隔开算式,传给bc
.37

[student@myhost ~]$ echo "obase=2;$a"|bc     #obase代表输出进制,输入进制默认10,用分号隔开数字,传给bc
100
[student@myhost ~]$ a=100
[student@myhost ~]$ echo "obase=10;ibase=2;$a" | bc   #ibase代表输入进制
4

[student@myhost ~]$ echo "sqrt(99)" | bc    #开方,输出为整数
9
[student@myhost ~]$ echo "9^2" | bc         #乘方
81

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值