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

Calculate a total from numbers produced by a for loop (running total)

我的作业是计算如果一个人的工资从每天 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 循环示例,您希望对每次迭代求和。为此,您将变量(在本例中为 total_accumulated)初始化为 0,然后将每次迭代的每个中间结果添加到该变量中,在循环完成后打印出最终的累积结果(对原始文件进行最少的编辑)代码):

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 在对你的问题的评论中指出的那样,这可以直接计算,并且这个答案仅针对带有循环的示例,因为这看起来像是经典的练习案例。

跟踪今天的工资和前一天的工资。以前计算今天的工资和今天的工资计算总计

init_sal = .01
total = 0
today_sal = 0
days = int(input("How many days will you work for pennies a day?"))

for x in range(1, days+1):
    if x == 1:
        today_sal = init_sal
        prev_sal = today_sal
    else:
        today_sal = prev_sal * 2
        prev_sal = today_sal
     total += today_sal
     print ('$', today_sal)

print (total)