2

我需要将一个数字舍入 1/32,然后将其舍入 1/100。我需要将其转换为一个单一的舍入规则(使用一个古老的程序......)。我可以乘除原始数字等等,只是不能四舍五入......

有没有办法在数学上做到这一点?

谢谢!

克罗斯

4

1 回答 1

2

如果您使用的任何东西都允许您定义函数,那么最易读的实现将是:

function round(x, interval){
    //implementation left as an exercise to the reader
}

#rounds x by interval1, then by interval2
function doubleRound(x, interval1, interval2){
    return round(round(x, interval1), interval2)
}

但是,如果您只有简单的算术,您可以将所有内容展开到一个语句中。

要将非负数 x 舍入到最接近的 N 区间,可以使用以下公式:

round(x,N) = floor((x + (N/2)) / N) * N

舍入两次,您将函数嵌套在自身中:

round(round(x, N1), N2) = floor(((floor((x + (N1/2)) / N1) * N1) + (N2/2)) / N2) * N2

所以要四舍五入 1/32 然后 1/100,你使用:

floor(((floor((x + ((1/32)/2)) / (1/32)) * (1/32)) + ((1/100)/2)) / (1/100)) * (1/100)
于 2012-05-03T14:23:12.433 回答