bash - 在 bash 中四舍五入

标签 bash shell rounding

<分区>

我正在服用 a challenge on hackerrank . 目标是:

read (int) N; then read N integers and print their avg to three decimal places.

代码如下:

#!/bin/bash
#file name:rdlp.sh
read N
s=0
i=1
while (($i<=$N))
     do
           read a
           s=$((s+a))
           i=$((i+1))
     done
s=$s/$N
echo  "scale=3;$s"|bc -l
fi

当我为某些输入运行代码时:

3 #(value of N)
4 #(N = 3 integers)
4
3

那么输出是3.666,但应该是3.667

所以问题是无论如何要让它正确(正确四舍五入),或者它只是那样工作吗?

(当上面的代码为 Testcase2 of the challenge at hackerrank 运行时问题出现了)

最佳答案

bc 使用 scale=x 向下舍入。
你可以打印:

$ printf "%.3f\n" $(echo  "scale=1000; 11/3"|bc -l)
3.667

或一些棘手的 bc 添加 0.0005:

$ echo  "scale=1000; v=11/3; v=v+0.0005; scale=3; v/1" | bc -l
3.667

关于bash - 在 bash 中四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51376985/

相关文章:

linux - Bash 复杂的管道依赖

linux - 在另一个环境中解析环境

python - 如何从 python 脚本执行 cd 命令并在新终端中执行其他命令?

bash - 用于发送 Mattermost 通知的 Shell 脚本不起作用

linux - 如何从包含特定字符串模式的行中提取第一个参数

r - 在 R 中如何舍入为 1、1.5、2 等而不是 1、2 或 1.1、1.2、1.3?

Excel向上或向下舍入到特定数字

Linux 启动 init.d 文件总是失败并跟随 bash,这是怎么回事?

parsing - 在 shell 脚本中解析 URL

python - 按特定数字进行浮点精度比较