我的任务是计算一个人每天的薪水从每天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天的总收入。
答案 0 :(得分:1)
我需要15天的总收入
作为标准的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在对您的问题的评论中所指出的那样,可以直接计算出该答案,并且该答案仅针对带有循环的示例,因为这看起来像是经典的锻炼案例。
答案 1 :(得分:0)
跟踪今天的工资和前一天的工资。以前用来计算今天的工资和今天用来计算总工资的
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)