在Bash shell环境中,可以利用 let、 (()) 、 [ ]、 expr 、 bc 进行数学运算
用法直接上代码,如下:
#! /bin/bash
echo "数学运算篇 START"
#基本运算----let
a=5;
b=4;
echo "a = $a , b = $b"
let c=a+b;
echo "a + b = $c"
let a++
echo "a++ = $a"
let b--
echo "b-- = $b"
let b+=a
echo "b+=a: b = $b"
#基本运算----[]
echo "a = $a, b = $b"
c=$[a+b]
echo "\$[a+b] = $c"
c=$[$a+$b]
echo "\$[\$a+\$b] = $c"
#基本运算----(())
c=$((a+b))
echo "\$((a+b))=$c"
#基本运算----expr
c=`expr 3 + 4` #注意+两侧的空格
echo "$c"
c=`expr $a + $b`
echo "$c"
#高级运算----bc
#1.计算浮点
echo "4 * 0.56" | bc
a=5.5
b=3.5
c=`echo "$a * $b" | bc`
echo "$a * $b = $c"
#2.设定小数精度
c=`echo "scale=3; $a * $b" | bc`
echo "scale=3; $a * $b = $c"
#3.进制转换
d=`echo "obase=2; $c" | bc`
echo "obase=2; $c = $d"
#4.高级函数
a=`echo "sqrt(100)" | bc`
echo "sqrt(100) = $a"
b=`echo "3^3" | bc`
echo "3^3 = $b"
echo "数学运算篇 END"
数学运算篇 START
a = 5 , b = 4
a + b = 9
a++ = 6
b-- = 3
b+=a: b = 9
a = 6, b = 9
$[a+b] = 15
$[$a+$b] = 15
$((a+b))=15
7
15
2.24
5.5 * 3.5 = 19.2
scale=3; 5.5 * 3.5 = 19.25
obase=2; 19.25 = 10011.0100000
sqrt(100) = 10
3^3 = 27
数学运算篇 END
注:内容多参照 《Linux Shell 脚步攻略》。 算学习笔记了。跟大家分享一下。
写的有不妥的地方,还望多多指正!
每天进步一点点!!!