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

2024-04-25 14:15:57 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: youforinputdaysamountwillnummany
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)

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

相关问题 更多 >