【问题标题】:bash bcmath functionsbash bcmath 函数
【发布时间】:2011-02-13 04:32:57
【问题描述】:

我在 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,而不是将其全部回显到单个实例。有什么解决方法吗?

【问题讨论】:

  • 我以交互方式获得 2.5。

标签: bash bcmath


【解决方案1】:

比例必须为零,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

【讨论】:

  • 缩放后缺少的 \n 是编辑复制粘贴代码后的拼写错误。我发现 if/else 块中的不同 return 语句比在任何地方写入并返回一次的变量更容易阅读,但在这种情况下 - 因为必须重置 scale - 单个 return 才有意义。
  • @Gordon:非常好。 bc 没有内置 int() 或其-l 库对我来说没有多大意义。 (或者地板/天花板。)
【解决方案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)                
}

【讨论】:

    猜你喜欢
    • 2021-06-15
    • 2018-04-16
    • 2011-06-11
    • 2013-04-19
    • 1970-01-01
    • 2018-05-18
    • 2017-09-16
    • 2018-03-22
    • 1970-01-01
    相关资源
    最近更新 更多