import random
total = 100
i = 1
while total > 0:
give = random.randint(1,10)
total -= give
i += 1
print('第',str(i),'个人,','收到',str(give),'元,','剩余',str(total),'元')
这样运行会出现负数。
第 24 个人, 收到 7 元, 剩余 -2 元
import random
total = 100
i = 1
while total > 0:
if total <10:
give = total
else:
give = random.randint(1,10)
print('第',str(i),'个人,','收到',str(give),'元,','剩余',str(total),'元')
total -= give
i += 1
这样会
第 1 个人, 收到 3 元, 剩余 100 元
第 18 个人, 收到 4 元, 剩余 4 元
应该改为
import random
total = 100
i = 1
while total > 0:
if total <10:
give = total
else:
give = random.randint(1,10)
print('第',str(i),'个人,','收到',str(give),'元,','剩余',str(total-give),'元')
total -= give
i += 1
1、注意total-=give的位置
2、在total小于10的时候,就不能减去1~10随机数了,否则会出现负数。