首页 > 解决方案 > 如何从 for 循环中计算总工资

问题描述

我想在用户输入一定天数后计算便士总数,并且 for 循环运行后给出每次迭代后的“便士”数量。我想总结所有右侧列,以便它以 $xx.xx 格式给出总计。

 numberOfDaysWorked = int(input ("Enter the amount of days worked: \n")) #Asking the user to enter the amount of days they have worked
 salary = 0.01 #setting the inital amount of pennies 
 total = 0.00
 print( "Day\tSalary\n---\t----" ) #printing out the titles for days and salary
 for currentDay in range(numberOfDaysWorked): 
      salary += 2 * salary # this is adding the amount of pennies earned that day to the total amount of pennies that will be used toward the total
      print (currentDay + 1, "\t", salary) #printing out the day (+1 to ensure progression from day1 to day2 to day3 etc. and then printing out the amount of pennies earned on that one day)


     print ("Total Pay: $", totalPay) 

标签: python

解决方案


for 循环的总和只是salaryfor 循环完成后的变量。不过检查你的数学。那个2好像不行。

编辑:

根据您的评论,只需totalPay在 for 循环中使用您的变量:

num_days_worked = int(input("Enter the amount of days worked: \n")) 
salary = 0.01 
total_pay = 0.00
print( "Day\tSalary\n---\t----" )
for current_day in range(num_days_worked):
    salary += 2 * salary 
    print (current_day + 1, "\t", salary)
    total_pay += salary

确保下次更好地解释您的问题,因此这里有很多不同的结果!


推荐阅读