数字四舍五入在公元前猛砸 [英] Rounding Numbers with bc in Bash
问题描述
我要计算与3位数字的平均值,四舍五入取,使用 BC
。
I want to compute an average with 3 decimal figures, rounded to nearest, using bc
.
例如:
3,3和5应产生3.667
average of 3, 3 and 5 should yield 3.667
和
3,3和4应该产生3.333
average of 3, 3 and 4 should yield 3.333
我试过:
echo "scale=3; $sum/$n+0.0005" | bc
但扩展
如我所料不表现。我能做些什么来解决我的问题?
but scale
doesn't behave as I expect. What can I do to solve my problem?
推荐答案
您伎俩添加 0.0005
不是一个坏主意。不过,这并不完全这样的。 比例
在内部使用时 BC
执行某些操作(如师)。
Your trick to add 0.0005
is not a bad idea. Though, it doesn't quite work that way. scale
is used internally when bc
performs some operations (like divisions).
在你的情况,这将是最好先进行分工,也许采用大扩展
或 -l </ code>开关置于
BC
1 (如果您的版本支持),然后加入 0.0005
然后设置 =规模3
和执行涉及比例
内部有截断执行。操作
In your case, it would be better to perform the division first, maybe using a large scale
or the -l
switch to bc
1 (if your version supports it), then add 0.0005
and then set scale=3
and perform an operation involving scale
internally to have the truncation performed.
是这样的:
`a=$sum/$n+0.0005; scale=3; a/1`
当然,你要进行不同的之
是正的还是负的。幸运的是, BC
有一些有条件的经营者。
Of course, you'll want to proceed differently whether sum
is positive or negative. Fortunately, bc
has some conditional operators.
`a=$sum/$n; if(a>0) a+=0.0005 else if (a<0) a-=0.0005; scale=3; a/1`
您会那么想用格式化这个答案的printf
。
You'll then want to format this answer using printf
.
裹函数圆形
(在这里你可以随意选择的十进制数字的号码):
Wrapped in a function round
(where you can optionally select the number of decimal figures):
round() {
# $1 is expression to round (should be a valid bc expression)
# $2 is number of decimal figures (optional). Defaults to three if none given
local df=${2:-3}
printf '%.*f\n' "$df" "$(bc -l <<< "a=$1; if(a>0) a+=5/10^($df+1) else if (a<0) a-=5/10^($df+1); scale=$df; a/1")"
}
试试吧:
gniourf$ round "(3+3+4)/3"
3.333
gniourf$ round "(3+3+5)/3"
3.667
gniourf$ round "-(3+3+5)/3"
-3.667
gniourf$ round 0
0.000
gniourf$ round 1/3 10
0.3333333333
gniourf$ round 0.0005
0.001
gniourf$ round 0.00049
0.000
1 与 -l </ code>开关,
比例
设置为 20
,这应该是足够足够了。
1 with the -l
switch, scale
is set to 20
, which should be plenty enough.
这篇关于数字四舍五入在公元前猛砸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!