我试图在Bash脚本中划分两个图像宽度,但Bash给我0作为结果:
RESULT=$(($IMG_WIDTH/$IMG2_WIDTH))
我确实研究了Bash指南,我知道我应该使用bc,在互联网上的所有例子中,他们都使用bc。在echo中,我试图把同样的东西放在我的SCALE中,但它不起作用。
以下是我在教程中找到的例子:
echo "scale=2; ${userinput}" | bc
我怎么能让巴斯给我0.5这样的浮点数呢?
我试图在Bash脚本中划分两个图像宽度,但Bash给我0作为结果:
RESULT=$(($IMG_WIDTH/$IMG2_WIDTH))
我确实研究了Bash指南,我知道我应该使用bc,在互联网上的所有例子中,他们都使用bc。在echo中,我试图把同样的东西放在我的SCALE中,但它不起作用。
以下是我在教程中找到的例子:
echo "scale=2; ${userinput}" | bc
我怎么能让巴斯给我0.5这样的浮点数呢?
当前回答
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.
其他回答
现在是尝试zsh的最佳时机,它是一个(几乎)bash超集,具有许多其他不错的特性,包括浮点数学。下面是你的例子在zsh中的样子:
% IMG_WIDTH=1080
% IMG2_WIDTH=640
% result=$((IMG_WIDTH*1.0/IMG2_WIDTH))
% echo $result
1.6875
这篇文章可能会帮助你:bash -值得切换到zsh随意使用?
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
让我们举个例子来理解,如果你想找到n个数组元素的平均值(当然平均值将是浮点数/小数)
declare -a arr
echo "How many numbers you want to enter?"
read n
echo "Enter the Array Elements"
for(( i=0 ; i<$n ; i++))
do
read array_elements
arr[$i]="$array_elements"
done
sum=0
for i in "${arr[@]}"
do
#sum and avg
sum=$(($sum + $i))
#average will come in decimals
avg=`echo $sum / $n | bc -l`
done
# Output results:
printf "Average of Array Elements %.2f:" $avg
因此,我们将使用"| bc -l"来进行浮动计算
对于那些试图用公认的答案计算百分比,但失去精度的人:
如果你运行这个:
echo "scale=2; (100/180) * 180" | bc
你只能得到99.00,这就失去了精确度。
如果你这样运行:
echo "result = (100/180) * 180; scale=2; result / 1" | bc -l
现在你得到99.99。
因为你只在打印的时候缩放。
参考此处