B样式中具有浮点值的C样式算术

Alb*_*tti 7 floating-point bash arithmetic-expressions

如何从这个bash脚本中获得正确的结果?

#!/bin/bash
echo $(( 1/2 ))
Run Code Online (Sandbox Code Playgroud)

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 ")
Run Code Online (Sandbox Code Playgroud)

Gil*_*not 12

不是单独使用浮动的正确工具,你应该使用:

bc <<< "scale=2; 1/2"
.50
Run Code Online (Sandbox Code Playgroud)

如果需要将结果存储在变量中:

res=$(bc <<< "scale=2; 1/2")
echo $res
Run Code Online (Sandbox Code Playgroud)