我在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为回显输出的每一行调用bc,而不是将其全部回显到单个实例。有什么解决方法吗?
发布于 2010-04-28 13:57:35
比例需要为零,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发布于 2011-07-22 04:34:59
我相信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)
}https://stackoverflow.com/questions/2726896
复制相似问题