gpt4 book ai didi

python - 使用嵌套循环在 while 循环中显示特定值?

转载 作者:太空宇宙 更新时间:2023-11-04 00:39:08 27 4
gpt4 key购买 nike

我有一个初始值,它每年以一定百分比 (5.5%) 增长。当初始值比原始值大 2、3 和 4 倍时,我的程序需要仅使用 while 循环打印出年份。到目前为止,我正在使用三个 while 循环来查找初始值何时比原始值大 2、3 和 4 倍,但到目前为止它可以工作,但它看起来确实是重复的。这是我目前所拥有的:

anum 123.45    #initial value
anum2 = initial * 2 #supposedly the numbers to indicate when the initial value has doubled, tripled, quadrupled etc.
anum3 = initial * 3
anum4 = initial * 4
initialYear = 2017
year = initialYear #year counter


while anum <= anum2: #make the loop stop before going further than two times greater than initial value
growth = anum * 0.055
anum = growth + anum
year += 1
print("Overall points will be 2 times 2017 points in {:d} years ({:d}).".format\
(year - 2017, year))

while anum <= anum3:
growth = anum * 0.055
anum = growth + anum
year += 1
print("Overall points will be 3 times 2017 points in {:d} years ({:d}).".format\
(year - 2017, year))

while anum <= anum4:
growth = anum * 0.055
anum = growth + anum
year += 1
print("Overall points will be 4 times 2017 points in {:d} years ({:d}).".format\
(year - 2017, year))

有没有一种方法可以让这个过程使用嵌套的 while 循环来减少它的整体重复性?

非常感谢任何帮助!

最佳答案

有一种方法可以使用嵌套循环来做到这一点。

我只是 python 的初学者,但这可能有用:

anum = 123.45
multiplier = 2


while multiplier < 5:
year = initialYear
for i in range(multiplier):
growth = anum * 0.055
anum = growth + anum
year += 1
print("multiplier =", multiplier)
multiplier += 1

希望对您有所帮助!

关于python - 使用嵌套循环在 while 循环中显示特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42631382/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com