简体   繁体   English

Bash比较浮点数

[英]Bash comparison floating number

I have an array: 我有一个数组:

pole_registru=("3" "8" "3.2" "6" "1" "3" "1.3" "3.3" "5.8" "12" "0" "3")

I need find elements in the array which are lower than 1 (including number with floating points) and count them (number of lower elements save to variable A ). 我需要在数组中找到小于1的元素(包括浮点数)并计算它们(较低元素的数量保存到变量A )。

I try: 我尝试:

for i in "${pole_registru[@]}"
do
  Hodnota="Value of actual: $i"
  compare=`echo "$i" | bc`
  echo --$compare--
  if [ $i < 1 ]; then (( A+=1 )); else (( A=A )); fi
  echo "$Value ($x) ($A)"
  sleep 1
done

Issue into console: 问题进入控制台:

./kontrolaNul.sh: řádek 33: 1: Folder or file does not.

Use bc directly to compare the numbers, like this 直接使用bc来比较数字,就像这样

pole_registru=("3" "8" "3.2" "6" "1" "3" "1.3" "3.3" "5.8" "12" "0" "3")
for i in "${pole_registru[@]}"
do
  Hodnota="Value of actual: $i"
  if (( $(bc <<< "$i<1") )) ; then (( A+=1 )); else (( A=A )); fi
  echo "$Value ($i) ($A)"
  sleep 1
done

The double parentheses construct is used to evaluate the string output of bc as a numerical value. 双括号构造用于将bc的字符串输出作为数值进行求值。 (I also changed $x to $i in the echo line) (我还在echo线中将$x更改$x $i

That gives: 这给了:

$ . t.sh 
 (3) (1)
 (8) (1)
 (3.2) (1)
 (6) (1)
 (1) (1)
 (3) (1)
 (1.3) (1)
 (3.3) (1)
 (5.8) (1)
 (12) (1)
 (0) (2)
 (3) (2)

This should solve your problem: 这应该可以解决您的问题:

for i in "${pole_registru[@]}"
do
  Hodnota="Value of actual: $i"
  compare=`echo "$i" | bc`
  echo --$compare--
  if [ `echo "$i < 1" | bc` -eq 1 ]; then (( A+=1 )); else (( A=A )); fi
  echo "$Value ($x) ($A)"
  sleep 1
done

Your immediate problem is that you're using < in your expression, which is the input file redirection operator - it's complaining because you have no file called 1 to get input from. 当前的问题是你在你的表达式中使用< ,这是输入文件重定向操作符 - 它正在抱怨,因为你没有名为1文件来获取输入。

If you change that to -lt , it will fix that problem. 如果将其更改为-lt ,它将解决该问题。

However, I don't think the bash numerics cater for floating point so you'll probably have more trouble after that. 但是,我不认为bash数字符合浮点数,所以你可能会遇到更多麻烦。

One way to get around that limitation is to use an external tool that does do floating point, use it to subtract one from your test number, then use the bash regular expression matching to detect a negative number: 要解决这个限制的一种方式是使用外部工具, 做浮点运算,用它来减去一个从测试号码,然后使用bash正则表达式匹配检测负数:

if [[ $(echo $i - 1 | BC_LINE_LENGTH=0 bc) =~ - ]] ; ...

The bc program is used to calculate x - 1 for your given x , don't worry about the BC_LINE_LENGTH setting, that's just to prevent line wrapping within bc ). bc程序用于计算给定x x - 1 ,不要担心BC_LINE_LENGTH设置,这只是为了防止bc换行)。

Then, if the result starts with a - character, the result was obviously less than zero (because x was less than one). 然后,如果结果以-字符开头,则结果显然小于零(因为x小于1)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM