Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在shell脚本中计算百分比_Shell - Fatal编程技术网

如何在shell脚本中计算百分比

如何在shell脚本中计算百分比,shell,Shell,我在shell代码中使用了下面的脚本行 百分比=echo“刻度=2;$DP*100/$SDC”| bc 它返回.16作为输出,但我需要它作为0.16兼容Posix的解决方案,使用bc: #!/bin/sh Percent="$(echo " scale=2; a = $DP * 100 / $SDC; if (a > -1 && a < 0) { print "'"-0"'"; a*=-1; } else if (a < 1 &&

我在shell代码中使用了下面的脚本行 百分比=
echo“刻度=2;$DP*100/$SDC”| bc

它返回.16作为输出,但我需要它作为0.16兼容Posix的解决方案,使用
bc

#!/bin/sh
Percent="$(echo "
  scale=2;
  a = $DP * 100 / $SDC;
  if (a > -1 && a < 0) { print "'"-0"'"; a*=-1; }
  else if (a < 1 && a > 0) print 0;
  a" | bc)"
Z shell可以本机执行此操作:

#!/bin/zsh
Percent="$(printf %.2f $(( DP * 100. / SDC )) )"
(点是指示zsh使用浮点数学所必需的。)

使用字符串操作的本机Posix解决方案(假设整数输入):

这将计算出1000倍于所需答案的结果,这样我们就拥有了最终分辨率为百分之一所需的所有数据。它加上五,所以我们可以正确地截断第千位。然后我们将临时变量
$total
定义为被截断的整数值,我们临时从
$Percent
中去掉它,然后我们附加一个点和小数,不包括千分之一(我们弄错了,这样我们可以正确地四舍五入百分之一)。

回答如下:
#!/bin/zsh
Percent="$(printf %.2f $(( DP * 100. / SDC )) )"
#!/bin/sh
#                                    # e.g. round down   e.g. round up
#                                    # DP=1 SDC=3        DP=2 SDC=3
Percent=$(( DP * 100000 / SDC + 5))  # Percent=33338     Percent=66671
Whole=${Percent%???}                 # Whole=33          Whole=66
Percent=${Percent#$Whole}            # Percent=338       Percent=671
Percent=$Whole.${Percent%?}          # Percent=33.33     Percent=66.67