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

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

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

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

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

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


当前回答

Bash可以很好地计算浮点结果,不需要任何其他程序。

Bash独立甚至可以精确地计算π到小数点后第九位。

例子:

calc=104348/33215

accuracy=9

calc99p9=$((10**$accuracy))*$calc
result99p9=$((calc99p9))
result=${result99p9: -${#result99p9}: -$accuracy}.${result99p9: -$accuracy}

echo Bash calculated pi to be $result

结果

Bash calculated pi to be 3.141592653

其他回答

你可以这样做:

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

更新20130926:你可以使用:

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

虽然在Bash中不能使用浮点除法,但可以使用定点除法。你所要做的就是把整数乘以10的次方,然后把整数部分除掉,用取模运算得到小数部分。根据需要舍入。

#!/bin/bash

n=$1
d=$2

# because of rounding this should be 10^{i+1}
# where i is the number of decimal digits wanted
i=4
P=$((10**(i+1)))
Pn=$(($P / 10))
# here we 'fix' the decimal place, divide and round tward zero
t=$(($n * $P / $d + ($n < 0 ? -5 : 5)))
# then we print the number by dividing off the interger part and
# using the modulo operator (after removing the rounding digit) to get the factional part.
printf "%d.%0${i}d\n" $(($t / $P)) $(((t < 0 ? -t : t) / 10 % $Pn))

它不是真正的浮点数,但如果你想在一次调用bc时设置多个结果…

source /dev/stdin <<<$(bc <<< '
d='$1'*3.1415926535897932384626433832795*2
print "d=",d,"\n"
a='$1'*'$1'*3.1415926535897932384626433832795
print "a=",a,"\n"
')

echo bc radius:$1 area:$a diameter:$d

计算半径为$1的圆的面积和直径

您可以通过-l选项使用bc (L字母)

RESULT=$(echo "$IMG_WIDTH/$IMG2_WIDTH" | bc -l)

我知道很老了,但太诱人了。所以,答案是:你不能……但你可以。让我们试试这个:

$IMG_WIDTH=1024
$IMG2_WIDTH=2048

$RATIO="$(( IMG_WIDTH / $IMG2_WIDTH )).$(( (IMG_WIDTH * 100 / IMG2_WIDTH) % 100 ))"

这样,在纯bash(不需要启动其他进程)中,在该点之后得到2位截断的数字(称为舍入到下位)。当然,如果你只需要这一点后面的一位数,你可以乘以10,然后对10取模。

它的作用:

First $((…))执行整数除法; 第二个$((…))对一个大100倍的数进行整数除法,本质上是将2位数字移到点的左边,然后(%)通过做模只得到这2位数字。

奖励轨道:bc版本× 1000在我的笔记本电脑上花了1.8秒,而纯bash版本花了0.016秒。