您的位置:首页 > 运维架构 > Shell

Shell脚本浮点运算

2016-09-07 14:52 183 查看
本文将介绍几种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 :



使用awk :



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

About me





- GitHub:AnSwErYWJ

- Blog:http://www.answerywj.com

- Email:yuanweijie1993@gmail.com

- Weibo:@AnSwEr不是答案

- CSDN:AnSwEr不是答案的专栏



This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell 脚本 浮点运算