如何将余数添加到现有的整数?

  • 本文关键字:整数 余数 添加 python
  • 更新时间 :
  • 英文 :


我们的任务是编写一个程序,从初始数量的塑料瓶(基本上是回收塑料)中找出可以制造的塑料瓶的总量。x是塑料瓶的初始数量,y是制造一个新塑料瓶所需的塑料瓶数量。

例如,我们需要2个瓶子来创建一个新瓶子。从最初的13个塑料瓶,我们可以创造25个新的塑料瓶(包括我们最初的13个塑料瓶)。逻辑是这样的:

13 // 2 = 6 rem. 1
7 // 2 = 3 rem. 1
4//2 = 2
2//2 = 1
13 (initial) + 6 + 3 + 2 + 1 = 25 bottles

我已经明白我们应该做什么,并创建了一个程序。然而,我有一个简单的问题,已经让我困惑了好几个小时。我不能将余数加到商中,这样当我再次除除时它将被包含。以下是我目前的进度:

x = 13  #just an example
y = 2  #just an example
bottles = [x]
sample = x
while sample // y != 0:
sample = sample // y
bottles.append(sample)
print(sum(bottles))

在应该是25的情况下打印23。我可以在代码中添加什么?

使用divmod()获得商和余数,并固定sample,使其应该是quotient + remainder:

x = 13
y = 2
bottles = [x]
sample = x
while sample // y != 0:
quotient, remainder = divmod(sample, y) # divmod(a, b) returns a tuple (a // b, a % b)
bottles.append(quotient)
sample = remainder + quotient
print(bottles)
print(sum(bottles))

输出:

[13, 6, 3, 2, 1]
25

这可以使用mod号,因为它给你一个商的余数。

x = 13
y = 2
bottles = [x]
mods = []
sample = x
while sample // y != 0:
sample = sample // y
mods.append(sample % y)
bottles.append(sample)
bSum = sum(bottles)
mSum = sum(mods)
print(bSum + mSum)

完成任务

x = 13
xy = x
y = 2
bottles = [x]
sample = x
sums=0
while sample! =1:
x = sample//y
xy = x
sample-=x
if sample==1 or sample==0:
if sample==1:
bottles.append(xy) 
break
bottles.append(xy) 
for i in bottles:
sums+=i
print(sums)

最新更新