在 Bash 中舍入除数 [英] Round a divided number in Bash

查看:30
本文介绍了在 Bash 中舍入除数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何从两个相除的数字中取整结果,例如

How would I round the result from two divided numbers, e.g.

3/2

和我一样

testOne=$((3/2))

$testOne 包含1",而它应该四舍五入为2"作为 3/2=1.5 的答案

$testOne contains "1" when it should have rounded up to "2" as the answer from 3/2=1.5

推荐答案

要在截断算术中进行四舍五入,只需将 (denom-1) 添加到分子即可.

To do rounding up in truncating arithmetic, simply add (denom-1) to the numerator.

示例,四舍五入:

N/2
M/5
K/16

示例,四舍五入:

(N+1)/2
(M+4)/5
(K+15)/16

要进行舍入到最近,请将 (denom/2) 添加到分子(一半将向上取整):

To do round-to-nearest, add (denom/2) to the numerator (halves will round up):

(N+1)/2
(M+2)/5
(K+8)/16

这篇关于在 Bash 中舍入除数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆