AnSwErYWJ's Blog

Shell脚本浮点运算

字数统计: 172阅读时长: 3 min
2016/09/05

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

Why

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

1
2
3
4
#!/bin/bash
a=59
b=60
expr $a / $b

运行结果 :

1
2
$ ./cal.sh
0

Plan A

使用bc进行处理。
代码 :

1
2
3
4
5
#!/bin/bash

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

运行结果 :

1
2
$ ./bc.sh
.9833

scale表示结果的小数精度。

Plan B

使用awk进行处理。
代码 :

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

运行结果 :

1
2
$ ./awk.sh
0.98

Compare

使用bc :
bc

使用awk :
awk

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

原文作者:AnSwErYWJ

原文链接:https://answerywj.com/2016/09/05/floating-point-operation-in-script/

发表日期:2016/09/05 14:09

版权声明:本文采用Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License进行许可.
Creative Commons License

CATALOG
  1. 1. Why
  2. 2. Plan A
  3. 3. Plan B
  4. 4. Compare