如何让 bc 打印尾随零?

Cle*_*t S 5 awk shell-script arithmetic bc text-formatting

我阅读了有关如何让 bc 打印第一个零的主题,但这并不是我想要的。我想要更多...

我想要一个返回带有八位十进制数字的浮点数的函数。我对任何解决方案持开放态度,使用 awk 或任何公平的方法。一个例子将说明我的意思:

hypothenuse () {
        local a=${1}
        local b=${2}
        echo "This is a ${a} and b ${b}"
        local x=`echo "scale=8; $a^2" | bc -l`
        local y=`echo "scale=8; $b^2" | bc -l`
        echo "This is x ${x} and y ${y}"
#       local sum=`awk -v k=$x -v k=$y 'BEGIN {print (k + l)}'`
#       echo "This is sum ${sum}"
        local c=`echo "scale=8; sqrt($a^2 + $b^2)" | bc -l`
        echo "This is c ${c}"
}
Run Code Online (Sandbox Code Playgroud)

有时,a并且b0.00000000,我需要在c返回时保留所有这些 0 。目前,当发生这种情况时,此代码会返回以下输出:

This is a 0.00000000 and b 0.00000000
This is x 0 and y 0
This is c 0
Run Code Online (Sandbox Code Playgroud)

我希望它打印

This is a 0.00000000 and b 0.00000000
This is x 0.00000000 and y 0.00000000
This is c 0.00000000
Run Code Online (Sandbox Code Playgroud)

帮助将不胜感激!

ImH*_*ere 10

在 bc 中,解决方案是除以 1:

$ bc -l <<<"scale=8; x=25*20; x"
500

$ bc -l <<<"scale=8; x=25*20; x/1"
500.00000000
Run Code Online (Sandbox Code Playgroud)

所以,你的脚本可能是这样的:

hypothenuse () {
        local a b c x y
        a=${1}; b=${2}
        echo "This is a ${a} and b ${b}"
        x=$(echo "scale=8; $a^2/1" | bc -l)
        y=$(echo "scale=8; $b^2/1" | bc -l)
        echo "This is x ${x} and y ${y}"
#       local sum=`awk -v k=$x -v k=$y 'BEGIN {print (k + l)}'`
#       echo "This is sum ${sum}"
        c=$(echo "scale=8; sqrt($a^2 + $b^2)/1" | bc -l)
        echo "This is c ${c}"
}
Run Code Online (Sandbox Code Playgroud)

我强烈建议你使用$(…)而不是`…`.

但即使这样也失败了,值为 0。

最好的解决方案是让 bc 的比例为 20(来自 bc -l),在对 bc 的一次调用中进行所有所需的数学运算,然后根据需要使用printf. 是的printf可以格式化浮点数。

假设 bash

hypothenuse () {  local a b c x y
                  a=${1:-0} b=${2:-0}
                  read -d '' x y c < <(
                  bc -l <<<"a=$a; b=$b; x=a^2; y=b^2; c=sqrt(x+y); x;y;c"
                  )

                  printf 'This is a %14.8f and b %14.8f\n' "$a" "$b"
                  printf 'This is x %14.8f and y %14.8f\n' "$x" "$y"
                  printf 'This is c %14.8f             \n' "$c"
               }
Run Code Online (Sandbox Code Playgroud)


小智 7

您可以使用以下方式外部化格式printf

printf "%0.8f" ${x}
Run Code Online (Sandbox Code Playgroud)

例子:

x=3
printf "%0.8f\n" ${x}
3.00000000
Run Code Online (Sandbox Code Playgroud)

注意:printf输出取决于您的区域设置。