在bash中,如何将两个变量相除并输出四舍五入至小数点后5位的答案? [英] In bash how do I divide two variables and output the answer rounded upto 5 decimal digits?
问题描述
我将两个变量作为输入,除以两个变量后,我想将输出舍入为5位小数位数.我已经尝试过这种方式->
I took two variables as input and after dividing them, I want to get the output rounded up to 5 decimal digits. I have tried this way ->
sum=12
n=7
output=$("scale=5;sum/n"|bc)
echo $output
我的代码未显示任何输出.我该怎么办?
My code isn't showing any output. What can I do??
TestCase:
如果 sum = 3345699
和 n = 1000000
然后(sum/n)= 3.345699
,则应将其更改为 3.34570
.
If sum=3345699
and n=1000000
then (sum/n)=3.345699
, it should be changed into 3.34570
.
推荐答案
此处的问题是您错过了提供的 echo
(或 printf
或其他任何东西)数据到 bc
:
The problem here is that you missed the echo
(or printf
or any other thing) to provide the data to bc
:
$ echo "scale=5; 12/7" | bc
1.71428
此外,正如cnicutar在评论中指出的那样,您需要使用 $
来引用变量. sum
是一个字符串, $ sum
是变量 sum
的值.
总之,您的代码段应该像这样:
Also, as noted by cnicutar in comments, you need to use $
to refer to the variables. sum
is a string, $sum
is the value of the variable sum
.
All together, your snippet should be like:
sum=12
n=7
output=$(echo "scale=5;$sum/$n" | bc)
echo "$output"
这将返回 1.71428
.
否则,使用"scale = 5; sum/n" | bc
,您只是在分配分配,并使 bc
失败:
Otherwise, with "scale=5;sum/n"|bc
you are just piping an assignment and makes bc
fail:
$ "scale=5;sum/n"|bc
bash: scale=5;sum/n: No such file or directory
然后,您说要对结果进行四舍五入,但这种情况目前还没有发生:
You then say that you want to have the result rounded, which does not happen right now:
$ sum=3345699
$ n=1000000
$ echo "scale=5;($sum/$n)" | bc
3.34569
这需要一种不同的方法,因为 bc
不会四舍五入.您可以将 printf
与%.Xf
一起使用以四舍五入为 X
十进制数字,这可以做到:
This needs a different approach, since bc
does not round. You can use printf
together with %.Xf
to round to X
decimal numbers, which does:
$ printf "%.5f" "$(echo "scale=10;$sum/$n" | bc)"
3.34570
看到我给它一个很大的比例,这样 printf
的小数点数就足以正确舍入.
See I give it a big scale, so that then printf
has decimals numbers enough to round properly.
这篇关于在bash中,如何将两个变量相除并输出四舍五入至小数点后5位的答案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!