将数字列表四舍五入为用户定义的步骤,同时保留其总和
我读了很多关于四舍五入数字的帖子,但我无法做到我想做的事:
我有一个正浮点数列表。 要使用的无符号整数 roundOffStep 是用户定义的。除此之外我无法控制。
我希望能够进行最准确的舍入,同时保留这些数字的总和,或者至少同时保持新的总和低于原始总和。
我该怎么做呢?我对算法很糟糕,所以这对我来说太棘手了。
谢谢。
编辑:添加测试用例:
FLOATS
29.20
18.25
14.60
8.76
2.19
sum = 73;
假设 roundOffStep = 5;
ROUNDED FLOATS
30
15
15
10
0
总和=70< 73 好的
I've been reading a lot of posts about rounding off numbers, but I couldn't manage to do what I want :
I have got a list of positive floats.
The unsigned integer roundOffStep to use is user-defined. I have no control other it.
I want to be able to do the most accurate rounding while preserving the sum of those numbers, or at least while keeping the new sum inferior to the original sum.
How would I do that ? I am terrible with algorithms, so this is way too tricky for me.
Thx.
EDIT : Adding a Test case :
FLOATS
29.20
18.25
14.60
8.76
2.19
sum = 73;
Let's say roundOffStep = 5;
ROUNDED FLOATS
30
15
15
10
0
sum = 70 < 73 OK
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
roundOffStep
倍数。rounded_number - Original_number
。按降序排列此差异列表,以便找到差异最大的数字。rounded_number - Original_number
的数字,然后从该数字中减去roundOffStep
。此过程应确保四舍五入后的数字尽可能接近原始数字,而不超过原始总和。
例如,
roundOffStep = 5
:总和太大,因此我们选择给出最大差值的数字(18.25,四舍五入为 20)并减去 5 得到 15。现在总和为 70,这样我们就完成了。
roundOffStep
normally.rounded_number - original_number
. Sort this list of differences in decreasing order so that you can find the numbers with the largest difference.rounded_number - original_number
, and subtractroundOffStep
from that number.This process should ensure that the rounded numbers are as close as possible to the originals, without going over the original sum.
Example, with
roundOffStep = 5
:The sum is too large, so we pick the number giving the largest difference (18.25 which was rounded to 20) and subtract 5 to give 15. Now the sum is 70, so we're done.