我试图在Bash脚本中划分两个图像宽度,但Bash给我0作为结果:

RESULT=$(($IMG_WIDTH/$IMG2_WIDTH))

我确实研究了Bash指南,我知道我应该使用bc,在互联网上的所有例子中,他们都使用bc。在echo中,我试图把同样的东西放在我的SCALE中,但它不起作用。

以下是我在教程中找到的例子:

echo "scale=2; ${userinput}" | bc 

我怎么能让巴斯给我0.5这样的浮点数呢?


当前回答

你可以这样做:

bc <<< 'scale=2; 100/3'
33.33

更新20130926:你可以使用:

bc -l <<< '100/3' # saves a few hits
33.33333333333333333333

其他回答

你可以这样做:

bc <<< 'scale=2; 100/3'
33.33

更新20130926:你可以使用:

bc -l <<< '100/3' # saves a few hits
33.33333333333333333333

There are scenarios in wich you cannot use bc becouse it might simply not be present, like in some cut down versions of busybox or embedded systems. In any case limiting outer dependencies is always a good thing to do so you can always add zeroes to the number being divided by (numerator), that is the same as multiplying by a power of 10 (you should choose a power of 10 according to the precision you need), that will make the division output an integer number. Once you have that integer treat it as a string and position the decimal point (moving it from right to left) a number of times equal to the power of ten you multiplied the numerator by. This is a simple way of obtaining float results by using only integer numbers.

稍微改进一下马文的回答:

RESULT=$(awk "BEGIN {printf \"%.2f\",${IMG_WIDTH}/${IMG2_WIDTH}}")

BC并不总是安装包。

你不能。Bash只处理整数;您必须委托给bc之类的工具。

作为bc的替代方案,您可以在脚本中使用awk。

例如:

echo "$IMG_WIDTH $IMG2_WIDTH" | awk '{printf "%.2f \n", $1/$2}'

在上面,“%.”2f”告诉printf函数返回一个小数点后两位的浮点数。我使用echo将变量管道作为字段,因为awk对它们正常操作。“$1”和“$2”表示输入awk的第一个和第二个字段。

你可以将结果存储为其他变量,使用:

RESULT = `echo ...`