hyytaojunming 发表于 2018-8-28 09:58:01

使用shell比较两个浮点数

  【参考链接】
  http://stackoverflow.com/questions/35734666/floating-point-number-comparison-in-bash-script
  【问题】
  I tried to compare floating point number by -gt but it says that point expecting integer value. That means it can not handle floating point number . Then i tried the following code
  我想用-gt比较两个浮点数大小,但屏幕却提示期望整数数值。
  这就意味着-gt不能处理浮点数。接着我使用以下代码
chi_square=4  
if [ "$chi_square>3.84" | bc ]
  
then
  
echo yes
  
else
  
echo no
  
fi
  但屏幕却输出以下错误信息:
line 3: [: missing `]'  
File ] is unavailable.
  
no
  Here the no is echoed but it should be yes. I think that's because of the error it's showing. can anybody help me.
  这里,执行结果本该是yes,此刻却提示no。我认为或许与提示的错误信息有关,谁能帮帮我呢?
  【解决办法】
  1.使用bc
  要想使用bc的话请参考以下用法:
chi_square=4  
if [[ $(bc -lexpr2
  The result is 1 if expr1 is strictly greater than expr2.
  2.使用awk
  Just use awk instead
$ awk -v chi_square=4 'BEGIN{print (chi_square > 3.84 ? "yes" : "no")}'  
yes
  

  
$ awk -v chi_square=3 'BEGIN{print (chi_square > 3.84 ? "yes" : "no")}'
  
no
  或许,你并不喜欢使用三目运算,我也提供了使用shell变量来解决此问题。
$ chi_square=4  
$ awk -v chi_square="$chi_square" 'BEGIN{
  
    if (chi_square > 3.84) {
  
      print "yes"
  
    }
  
    else {
  
      print "no"
  
    }
  
}'
  
yes
  

  
$ echo "$chi_square" |
  
awk '{
  
    if ($0 > 3.84) {
  
      print "yes"
  
    }
  
    else {
  
      print "no"
  
    }
  
}'
  
yes
  
或者
  
$ echo "$chi_square" | awk '{print ($0 > 3.84 ? "yes" : "no")}'
  
yes


页: [1]
查看完整版本: 使用shell比较两个浮点数