【问题标题】:difference between bc and bc -l in bash when i try to find modulus of a number [closed]当我尝试查找数字的模数时,bash中的bc和bc -l之间的区别[关闭]
【发布时间】:2020-09-12 12:35:20
【问题描述】:

为什么当我执行命令时 Unix 给出结果 0: echo "7%2" | bc -l 并在我执行命令时给出结果 1: echo "7%2" |公元前

【问题讨论】:

  • 请参阅“数学库”标题下的 man 1 bc。有一些函数需要这个库,另外它会影响 scale 默认为 20。Modulo 不需要。
  • 我编辑了标签。这纯粹是关于bc,而不是之前标记的unixbash

标签: bc


【解决方案1】:

为什么当我执行命令时 Unix 给出结果 0: echo "7%2" | bc -l

来自bc手册:

If  bc  is  invoked with the -l option, a math library is preloaded and the default scale is set to 20. 

   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.

所以:

 a=7    b=2
 a/b = 7 / 2 = 3.50000000000000000000000000000000000000000000000000 
 7%2 = a-(a/b)*b =
     = 7 - (7/2)*2 = 
     = 7 - (3.50000000000000000000000000000000000000000000000000) * 2 =
     = 7 - 7 =
     = 0

并在我执行命令时给出结果 1:echo "7%2" |公元前

来自bc手册:

scale 定义了一些操作如何使用小数点后的数字。 scale的默认值为0。

在这种情况下:

a=7    b=2
a/b = 7 / 2 = 3 # scale is 0, rounds down
a%b = a-(a/b)*b =
    = 7 - (7/2)*2 =
    = 7 - 3 * 2 = 
    = 7 - 6 =
    = 1

因为7/2是用不同的比例计算的,所以结果表达式不同。

【讨论】:

    猜你喜欢
    • 2015-02-12
    • 2021-04-16
    • 1970-01-01
    • 2011-01-20
    • 2017-08-14
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多