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

2024-10-02 12:37:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如,我们需要两个瓶子来创建一个新瓶子。从最初的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。我可以在代码中添加什么


Tags: sample程序an瓶子数量example逻辑initial
3条回答

这就行了

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)

使用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)

相关问题 更多 >

    热门问题