Division in script and floating-point

匿名 (未验证) 提交于 2019-12-03 02:24:01

问题:

I would like to do the following operation in my script:

1 - ((m - 20) / 34) 

I would like to assign the result of this operation to another variable. I want my script use floating point math. For example, for m = 34:

results = 1 - ((34 - 20) / 34) == 0.588 

回答1:

You could use the bc calculator. It will do arbitrary precision math using decimals (not binary floating point) if you set increease scale from its default of 0:

$ m=34 $ bc 

The -l option will load the standard math library and default the scale to 20:

$ bc -l 

You can then use printf to format the output, if you so choose:

printf "%.3f\n" "$(bc -l ...)" 


回答2:

Bash does not do floating point math. You can use awk or bc to handle this. Here is an awk example:

$ m=34; awk -v m=$m 'BEGIN { print 1 - ((m - 20) / 34) }' 0.588235 

To assign the output to a variable:

var=$(awk -v m=$m 'BEGIN { print 1 - ((m - 20) / 34) }') 


回答3:

Teach bash e.g. integer division with floating point results:

#!/bin/bash  div ()  # Arguments: dividend and divisor {         if [ $2 -eq 0 ]; then echo division by 0; exit; fi         local p=12                            # precision         local c=${c:-0}                       # precision counter         local d=.                             # decimal separator         local r=$(($1/$2)); echo -n $r        # result of division         local m=$(($r*$2))         [ $c -eq 0 ] && [ $m -ne $1 ] && echo -n $d         [ $1 -eq $m ] || [ $c -eq $p ] && return         local e=$(($1-$m))         let c=c+1         div $(($e*10)) $2 }        result=$(div 1080 633)                  # write to variable     echo $result      result=$(div 7 34)     echo $result      result=$(div 8 32)     echo $result      result=$(div 246891510 2)     echo $result      result=$(div 5000000 177)     echo $result 

Output:

    1.706161137440     0.205882352941     0.25     123445755     28248.587570621468 


回答4:

echo $a/$b|bc -l 

gives the result.

Example:

read a b echo $a/$b|bc -l 

Enter a & b value as 10 3, you get 3.3333333333

If you want to store the value in another variable then use the code

read a b c=`echo $a/$b|bc -l` echo $c 

It also gives the same result as above. Try it...



回答5:

Use this script open this file with favorite editor like:

$ sudo vim /usr/bin/div 

Then paste this code:

#!/bin/bash # Author: Danial Rikhteh Garan (danial.rikhtehgaran@gmail.com)  if [[ -z "$1" ]] || [[ -z "$2" ]]; then     echo "Please input two number"     echo "for 100/50 use: div 10 50"     exit 1; fi  div=$(echo "$1/$2" | bc -l); echo 0$div | sed 's/[0]*$//g' 

Now chmod it to 755:

$ sudo chmod 755 /usr/bin/div 

Now use it:

$ div 5 100 0.05 

In your script you can use this:

var=$(div 5 100); echo "$var" 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!