bash,bc模不适用于-l标志 [英] bash, bc modulo does not work with -l flag
问题描述
因此,我尝试使用bc
来计算一些对数,但是我还需要使用它来计算某些事物的模数.在编写脚本的同时,我启动了bc
对其进行测试.
So I am trying to use bc
to calculate some logarithms but I also need to use it to calculate the modulus for something. Whilst making my script, I launched bc
to test it.
没有任何标志,bc <<< "3%5"
当然会返回3
.
Without any flags, bc <<< "3%5"
of course returns 3
.
但是使用bc -l
(加载数学库,以便我可以计算对数),a%b
的任何计算都会返回0
,其中a
和b
可以是除0
之外的任何数字.
But with bc -l
(loads math library so I can compute logarithms) any calculation of a%b
returns 0
where a
and b
can be any number but 0
.
发生了什么事?
推荐答案
这是因为,根据手册:
expr % expr
The result of the expression is the "remainder" and it is com‐
puted in the following way. To compute a%b, first a/b is com‐
puted to scale digits. That result is used to compute a-(a/b)*b
to the scale of the maximum of scale+scale(b) and scale(a). If
scale is set to zero and both expressions are integers this
expression is the integer remainder function.
使用-l
标志运行bc
时,scale
设置为20
.要解决此问题:
When you run bc
with the -l
flag, scale
is set to 20
. To fix this:
bc -l <<< "oldscale=scale; scale=0; 3%5; scale=oldscale; l(2)"
我们首先将scale
保存在变量oldscale
中,然后将scale
设置为0
以执行一些算术运算,并计算ln
,我们将scale
设置回原来的值.这将输出:
We first save scale
in variable oldscale
, then set scale
to 0
to perform some arithmetic operations, and to compute a ln
we set scale
back to its old value. This will output:
3
.69314718055994530941
根据需要.
这篇关于bash,bc模不适用于-l标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!