Bash中具有浮点值的C风格算术 [英] C style arithmetic with floating point values in Bash
本文介绍了Bash中具有浮点值的C风格算术的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从此bash脚本中获得正确的结果?
How can I have the right result from this bash script?
#!/bin/bash
echo $(( 1/2 ))
结果是0
!因此,我尝试使用这些方法,但没有成功:
I get 0
as result! So I tried to use these but without success:
$ echo $(( 1/2.0 ))
bash: 1/2.0 : syntax error: invalid arithmetic operator (error token is ".0 ")
$ echo $(( 1.0/2 ))
bash: 1.0/2 : syntax error: invalid arithmetic operator (error token is ".0/2 ")
推荐答案
bash 并不是单独使用 floats 的正确工具,您应该使用
bash is not the right tool alone to use floats, you should use bc with it :
bc <<< "scale=2; 1/2"
.50
如果需要将结果存储在变量中:
If you need to store the result in a variable :
res=$(bc <<< "scale=2; 1/2")
echo $res
这篇关于Bash中具有浮点值的C风格算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文