【问题标题】:Calculate a total from numbers produced by a for loop (running total)根据 for 循环产生的数字计算总数(运行总数)
【发布时间】:2018-06-25 00:42:49
【问题描述】:

我的任务是计算如果一个人的薪水从每天 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 天的总收入。

【问题讨论】:

  • total_salary = 2^days - 1

标签: python cumulative-sum


【解决方案1】:

我需要 15 天内赚取的总金额

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

【讨论】:

    【解决方案2】:

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

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-23
      • 1970-01-01
      相关资源
      最近更新 更多