bash 浮点运算
Integers are natively supported in Bash shell. However, what if we use floating point in Bash shell?
Bash shell本机支持整数。 然而,如果我们使用浮什么点中的Bash shell?
The short and direct answer is using ‘bc‘ command – “An arbitrary precision calculator language.”
简短而直接的答案是使用“ bc ”命令 -“任意精度的计算器语言。”
Just run bc and enter some floating point calculation expression, such as “1.2+8.2”, bc will give the result.
只需运行bc并输入一些浮点计算表达式,例如“ 1.2 + 8.2”,bc就会给出结果。
In a script, we certainly need a more automatic way. This is a piece of simple script:
在脚本中,我们当然需要一种更自动的方式。 这是一个简单的脚本:
$ echo "scale=4; $*" | bc -q
For example, to calculate “1.2+8.2”
例如,要计算“ 1.2 + 8.2”
$ echo "scale=4; 1.2+8.2" | bc -q
and you will get 9.4 .
您将获得9.4。
“By default bc outputs its result with no digits to the right of the decimal point and without a decimal point. To change this you have to change one of bc‘s builtin variables: scale. This is where the “language” features of bc are relevant, in bc as in C statements are separated by semi-colons.”
“默认情况下, bc输出的结果在小数点右边没有数字,并且没有小数点。 要更改此设置,您必须更改bc的内置变量之一: scale 。 这是与bc的“语言”功能相关的地方,在bc中,如C语句中的分号分隔。
For more detailed tutorial on bc, I suggest: Floating Point Math in Bash by Mitch Frazier.
有关bc的详细教程 ,我建议:Mitch Frazier撰写的Bash中的浮点数学 。
翻译自: https://www.systutorials.com/floating-point-in-bash-shell/
bash 浮点运算