Arithmetic with floating point

眉间皱痕 提交于 2020-07-22 21:41:01

问题


I have a very simple problem, i'm making a function that receives some floating point numbers and make a couple of operations with them at the beggining. Something like this:

function x {
    A=$1
    B=$2

# here i need a ratio, so i do, let's say..

    sum=$(($A + $B))
    C=$(($A / $sum))

[lots of code here]

}

The problem is that $1 and $2 are floating point numbers, or even if they're ints, the ratio it's very likely not to be an int, so i don't know how to operate them under bash.

I tried with a bc pipe when defining the sum and the ratio, but it outputs nothing.

Any idea is welcome! Thanks!


回答1:


bc is a good idea. I don't know what you've tried; one way to do it is

C=$(echo "$A / $sum" | bc -l)



回答2:


With bc;

var=$(echo "scale=10; $A / $num" | bc)

echo $var

Note the scale parameter to tell bc how many decimal you want



来源:https://stackoverflow.com/questions/27586277/arithmetic-with-floating-point

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