Bash中带浮点值的C风格算法
如何从这个bash脚本中获得正确的结果Bash中带浮点值的C风格算法,bash,floating-point,arithmetic-expressions,bc,Bash,Floating Point,Arithmetic Expressions,Bc,如何从这个bash脚本中获得正确的结果 #!/bin/bash echo $(( 1/2 )) 结果我得到0!因此,我尝试使用这些,但没有成功: $ 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 (
#!/bin/bash
echo $(( 1/2 ))
结果我得到0
!因此,我尝试使用这些,但没有成功:
$ 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 ")
不是单独使用浮动的正确工具,您应该使用它:
bc <<< "scale=2; 1/2"
.50
bc我有一次偶然发现了一段不错的代码,这段代码在某种程度上利用了sputnick提出的建议,但它围绕着一个bash
函数:
function float_eval()
{
local stat=0
local result=0.0
if [[ $# -gt 0 ]]; then
result=$(echo "scale=$float_scale; $*" | bc -q 2>/dev/null)
stat=$?
if [[ $stat -eq 0 && -z "$result" ]]; then stat=1; fi
fi
echo $result
return $stat
}
然后,您可以将其用作:
c=$(float_eval "$a / $b")
c=$(float_eval "$a / $b")