bash bcmath函数

时间:2010-04-28 04:54:02

标签: bash bcmath

我在Bash脚本中有两个GNU bc函数。

BC_CEIL="define ceil(x) { if (x>0) { if (x%1>0) return x+(1-(x%1)) else return x } else return -1*floor(-1*x) }\n"
BC_FLOOR="define floor(x) { if (x>0) return x-(x%1) else return -1*ceil(-1*x) }\n"
echo -e "scale=2"$BC_CEIL$BC_FLOOR"ceil(2.5)" | bc

这两个功能在交互式bc中运行良好。 bc似乎不允许在一行之间分隔多个函数;虽然,所以我必须回应-n | bc,每个函数末尾都有换行符。上面的输出是2.5,而不是我自己输入bc -i时得到的3.0。似乎bash为每一行echo输出调用bc,而不是将它全部回显给单个实例。有没有解决方法呢?

2 个答案:

答案 0 :(得分:2)

x%1的工作量必须为零才能生效。通常只能从函数返回一个。

define ceil(x) { auto savescale; savescale = scale; scale = 0; if (x>0) { if (x%1>0) result = x+(1-(x%1)) else result = x } else result = -1*floor(-1*x);  scale = savescale; return result }
define floor(x) { auto savescale; savescale = scale; scale = 0; if (x>0) result = x-(x%1) else result = -1*ceil(-1*x);  scale = savescale; return result }

在scale语句之后需要换行符:

echo -e "scale=2\n"$BC_CEIL$BC_FLOOR"ceil(2.5)" | bc

答案 1 :(得分:2)

我认为1.不正确。 if()比较需要为X >= 0

我觉得这很有效

define ceil(x) {                         
    if (x >= 0) { if (x%1>0) return x+(1-(x%1)) else return x } 
    else return -1*floor(-1*x)               
}
define floor(x) {                        
    if (x >= 0) return x-(x%1)               
    else return -1*ceil(-1*x)                
}