首页 > 解决方案 > 获得 3 个不同数字之和的整数/舍入问题

问题描述

a = 1541
b = 1575
c = 1512
# I want to ratio the sum of these numbers to 128

total = a + b + c

rounded_a = round(a*128/total) # equals 43
rounded_b = round(b*128/total) # equals 44
rounded_c = round(c*128/total) # equals 42

total_of_rounded = rounded_a + rounded_b + rounded_c # equals 129 NOT 128

# I tried the floor

floor_a = math.floor(a*128/total) # equals 42
floor_b = math.floor(b*128/total) # equals 43
floor_c = math.floor(c*128/total) # equals 41

total_of_floor = floor_a + floor_b + floor_c # equals 126 NOT 128

# The exact values
# a: 42.62057044
# b: 43.56093345
# c: 41,81849611

问题是,我怎样才能达到总数 128?

注意:我应该保持整数,而不是浮点数。注意 2:我可以编写一个校正函数,比如在总数中加上 +1,但对我来说似乎不合适。

标签: pythonpython-3.xmathnumbersrounding

解决方案


一种可能性:四舍五入ab然后将缺少的部分添加到c.

a = 1541
b = 1575
c = 1512
total = a + b + c  # 4628

ra = a * 128 // total
rb = b * 128 // total
rc = (c * 128 + (a * 128)%total + (b*128)%total) // total

print(ra,rb,rc)
# (42, 43, 43)
print(ra+rb+rc)
# 128

推荐阅读