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

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

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

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

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

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


当前回答

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

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

BC并不总是安装包。

其他回答

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

$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秒。

它不是真正的浮点数,但如果你想在一次调用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的圆的面积和直径

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

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

BC并不总是安装包。

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.

红利=除数×商+余数

我们来计算商和余数。 以及将这些字符串连接到一个变量中。

新方法只对log_decimal除数有效:

function main() {
  bar=10030
  divisor=100
  # divisor=50

  quotient=$((bar / divisor))
  # remainder=$((bar - v_int * divisor))
  remainder=$((bar % divisor))
  remainder_init=$remainder

  printf "%-15s --> %s\n" "quotient" "$quotient"
  printf "%-15s --> %s\n" "remainder" "$remainder"

  cnt=0
  while :; do
    remainder=$((remainder * 10))
    aux=$((remainder / divisor))
    printf "%-15s --> %s\n" "aux" "$aux"
    [[ aux -ne 0 ]] && break
    ((cnt += 1))
    printf "%-15s --> %s\n" "remainder" "$remainder"
  done
  printf "%-15s --> %s\n" "cnt" "$cnt"
  printf "%-15s --> %s\n" "aux" "$aux"

  printf $quotient
  printf "."
  for i in $(seq 1 $cnt); do printf "0"; done
  printf $remainder_init
}
clear
main

旧的错误方式:

bar=1234 \
&& divisor=1000 \
    && foo=$(printf "%s.%s" $(( bar / divisor )) $(( bar % divisor ))) \
    && printf "bar is %d miliseconds or %s seconds\n" $bar $foo

输出:bar为1234毫秒或1.234秒