巴什C形式的算术浮点值 [英] Bash C style arithmetic with floating point value
本文介绍了巴什C形式的算术浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怎么能有从这个bash脚本正确的结果?
#!/斌/庆典
回声$((1/2))
我得到 0
的结果!于是,我就用这些,但没有成功:
$回声$((1 / 2.0))
庆典:1 / 2.0:语法错误:无效的算术运算符(错误标记为.0)
$回声$((1.0 / 2))
庆典:1.0 / 2:语法错误:无效的算术运算符(错误标记是.0 / 2)
解决方案
的庆典是不正确的工具单独使用的浮动的,你应该使用的 BC 吧:
BC<<< 规模= 2; 1/2
0.50
如果您需要将结果存储在一个变量:
RES = $(BC<<<规模= 2; 1/2)
回声$水库
How can I have the right result from this bash script?
#!/bin/bash
echo $(( 1/2 ))
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 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
这篇关于巴什C形式的算术浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文