LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 856|回复: 9

bc的问题[基本解决]

[复制链接]
发表于 2004-4-20 11:09:27 | 显示全部楼层 |阅读模式
奇怪,我现在用bc得到的结果全都是整型数据
例如
$ echo "9.5/5.0"|bc
1
$ echo "9.5/4.0"|bc
2
发表于 2004-4-20 11:29:15 | 显示全部楼层
echo "9.5/5.0"|bc -l
发表于 2004-4-20 11:38:05 | 显示全部楼层

回复: bc的问题

最初由 scopio 发表
奇怪,我现在用bc得到的结果全都是整型数据
例如
$ echo "9.5/5.0"|bc
1
$ echo "9.5/4.0"|bc
2

  1. echo "[color=red]scale=2[/color];9.5/5.0"|bc
复制代码

#保留小数点后两位
 楼主| 发表于 2004-4-21 22:05:37 | 显示全部楼层
谢谢谢谢:)
 楼主| 发表于 2004-4-26 03:10:05 | 显示全部楼层
奇怪,我发现用乘法怎么就不起作用了呢?

$ echo "scale=2;13*0.254"|bc
3.302
发表于 2004-4-26 12:14:02 | 显示全部楼层
scale是区分不同的情况的,见manual:
Addition, subtraction
          The scale of the result is the larger of the scales of the two
          operands. There is never any truncation of the result.

  Multiplication
          The scale of the result is never less than the maximum of the two
          scales of the operands, and never more than the sum of the scales
          of the operands, and subject to those two restrictions, the scale
          of the result is set equal to the contents of the internal
          quantity, scale.

  Division
          The scale of a quotient is the contents of the internal quantity,
          scale.

  Modulo  The scale of a remainder is the sum of the scales of the quotient
          and the divisor.

  Exponentiation
          The result of an exponentiation is scaled as if the implied
          multiplications were performed. An exponent must be an integer.

  Square Root
          The scale of a square root is set to the maximum of the scale of the
          argument and the contents of scale.

  All of the internal operations are actually carried out in terms of
  integers, with digits being discarded when necessary. In every case where
  digits are discarded truncation is performed without rounding.

  The contents of scale must be no greater than 99 and no less than 0. It is
  initially set to 0.

这是一段中文的解释:
加法,减法结果的标度(精度)是大的二个操作数的标度(两个操作数中的精度最高者)。 有从未结果的任一截(不会自动截取数位)。
  增殖(乘法)结果的标度比操作数的二个标度的最大值比操作数的标度的总和从未是较少(不会比两个操作数的精度小),和从未更多,并且依于那些二个制约,结果的标度被设置相等与内部数量的内容,标度。
  分部商数(除法)的标度是内部数量的内容,标度(由scale确定)。
  模数剩下的人的(求模)标度是商数和除数的标度的总和(是两个操作数的精度和)。
  取幂(幂)取幂的结果被称好象含蓄的增殖执行了(隐含按乘法规则执行)。 方次数必须是整数。
  方根一个方根的标度被设置对论据和标度内容的标度的最大值。
  所有内部操作实际上被执行根据整数,与数字被放弃如果必要。 数字被放弃的地方截每次执行没有环绕。
  标度(精度)内容必须是没有(不)大于99 和没有少于(不小于)0 。 它最初被设置到(初值为)0 。
 楼主| 发表于 2004-4-26 14:56:33 | 显示全部楼层
中文版是不是软件翻译的?头都晕了~
 楼主| 发表于 2004-4-26 14:58:00 | 显示全部楼层
谢谢javalee,那请问如何指定结果的精度呢?
 楼主| 发表于 2004-4-26 15:01:48 | 显示全部楼层
printf %.0f $(echo "13*0.254"|bc)

这样好象可以:)
发表于 2004-4-26 15:55:52 | 显示全部楼层
用awk的printf函数也可
awk 'BEGIN{printf "%.Nf\n",n1*n2}'
其中,N为小数点后N位,
or
printf "%.Nf\n" floatnum
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表