Shell脚本浮点运算

本文将介绍几种Linux下通过Shell脚本进行浮点数计算的方法。

Why

Bash Shell本身不具备处理浮点计算的能力, 如expr命令只支持整数运算 :

#!/bin/bash
a=59
b=60
expr $a / $b

运行结果 :

$ ./cal.sh
0
$

Plan A

使用bc进行处理。
代码 :

#!/bin/bash

a=59
b=60
echo "scale=4; $a / $b" | bc

运行结果 :

$ ./bc.sh
.9833
$

scale表示结果的小数精度。

Plan B

使用awk进行处理。
代码 :

#!/bin/bash
a=59
b=60
awk 'BEGIN{printf "%.2f\n",('$a'/'$b')}'

运行结果 :

$ ./awk.sh
0.98
$

Compare

使用bc :
bc

使用awk :
awk

可以看出使用awk的效率更高,特别是运算次数比较大时。

About me

forthebadge
- GitHub:AnSwErYWJ
- Blog:http://www.answerywj.com
- Email:[email protected]
- Weibo:@AnSwEr不是答案
- CSDN:AnSwEr不是答案的专栏

Creative Commons License This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。

猜你喜欢

转载自blog.csdn.net/u011192270/article/details/52459588