gpt4 book ai didi

python - 根据 for 循环生成的数字计算总计(运行总计)

转载 作者:行者123 更新时间:2023-12-01 09:18:32 25 4
gpt4 key购买 nike

我的任务是计算如果一个人的工资从每天 1 美分开始,每天翻倍,他会得到多少钱。

days = int(input("How many days will you work for pennies a day?"))
total_amount = ((2 ** (days - 1)) / 100)
print("Days Worked | Amount Earned That Day")
for num in range(days):
total_amount = format((2 ** (num) / 100), ',.2f')
print(num + 1, "|", "$", total_amount)

如果我输入 15 天,我可以看到每天的工资,但我需要这 15 天的总收入。

最佳答案

I need the total amount earned over the 15 days

作为标准for您想要在每次迭代中求和的循环示例。为了实现这一点,您用 0 初始化变量(在本例中为 total_accumulated ),然后将每次迭代的每个中间结果添加到该变量中,循环完成后,您将像这样打印出最终的累积结果(对原始代码进行最少的编辑) :

days = int(input("How many days will you work for pennies a day?"))
total_amount = ((2 ** (days - 1)) / 100)
total_accumulated = 0
print("Days Worked | Amount Earned That Day")
for num in range(days):
current_pay = (2 ** (num) / 100)
total_accumulated += current_pay
total_amount = format(current_pay, ',.2f')
print(num + 1, "|", "$", total_amount)
print("Total accumulated:", str(total_accumulated))

正如 @NiVeR 对您的问题的评论中所指出的,这可以直接计算,并且该答案仅针对带有循环的示例,因为这看起来像是经典的练习案例。

关于python - 根据 for 循环生成的数字计算总计(运行总计),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51011700/

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