开发者

Arithmetic problem with shell script

I've got some issues on scripting... if someone could help me, it would be really good !

My script has:

VISITS=$((WR + RD));
SERVICE_DEMAND=$((VISITS*SERVICE_DEMAND));

And I'm开发者_如何学编程 getting this error:

./calc_serv_demand.sh: line 12: 0.0895406: syntax error: invalid arithmetic operator (error token is ".0895406")

Can someone help me?

I think it's because the bash works only with integer... I need to use float values, though.

thanks in advance


Problem solved:

VISITS=$(echo $WR + $RD | bc); echo $VISITS

SERVICE_DEMAND=$(echo $VISITS '*' $SERVICE_TIME | bc); echo $SERVICE_DEMAND


You can use bc to do your floating point calculations, i.e.

echo $WR + $RD | bc

and so on.


Instead of using bc, consider switching to a better programming language. Bash is simply unsuited for mathematics.


Use bc to do float calculations in Bash.


To set the precision (number of digits of the answer to the right of the decimal point), write:

WR=5
RD=7
VISITS=$[WR+RD]
SERVICE_DEMAND=.0895406
SERVICE_DEMAND=`echo "scale=5; $VISITS * $SERVICE_DEMAND" |bc -l`
echo Service Demand = $SERVICE_DEMAND

This outputs:

Service Demand = 1.0744872

The scale=5 sets 5 digits of precision; the backquotes cause the contained expression to be evaluated and the ouput (from the bc -l) to be assigned to your variable.


You'll have to use an external program like bc to do floating-point math in your scripts.

Something like:

echo ($WR+$RD)*$SERVICE_DEMAND | bc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜