使用while循环时,如何计算运行总数?

2024-07-04 08:00:27 发布

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

我很难理解这段代码(我是新来的,所以请温柔一点),试图编写一个跟踪卡路里的程序,但我无法获得代码:

caloriesPerMeal = int(input('Enter calories eaten per meal: '))

当它回顾并再次询问我是否要进入另一顿饭时添加到自身中(如下所示):

keepGoing = input('Do you want to enter another meal? (Enter yes or no) ')

我的全部代码是:

keepGoing = 'yes'
totalCalories = 0
#Calories per Day
maxCaloriesPerDay = int(input('How many calories per day would you like to consume? '))
while keepGoing == 'yes':
    #Get number of calories per meal
    caloriesPerMeal = int(input('Enter calories eaten per meal: '))
    totalCalories += totalCalories + caloriesPerMeal
#See if user wants to input another meal
    keepGoing = input('Do you want to enter another meal? (Enter yes or no) ')
#Calculate calories under/over per day
if totalCalories >= maxCaloriesPerDay:
    print('You are', maxCaloriesPerDay - totalCalories, 'calories over your maximum calories per 
 day.')
elif totalCalories <= maxCaloriesPerDay:
     print('You are', maxCaloriesPerDay - totalCalories, 'calories under your maximum calories per 
day. ')

Tags: to代码youinputyesintenterday
2条回答
keepGoing = 'yes'
totalCalories = 0
#Calories per Day
maxCaloriesPerDay = int(input('How many calories per day would you like to consume? '))
while keepGoing == 'yes':
    #Get number of calories per meal
    caloriesPerMeal = int(input('Enter calories eaten per meal: '))
    totalCalories += caloriesPerMeal
#See if user wants to input another meal
    keepGoing = input('Do you want to enter another meal? (Enter yes or no) ')
#Calculate calories under/over per day
if totalCalories >= maxCaloriesPerDay:
    print('You are', maxCaloriesPerDay - totalCalories, 'calories over your maximum calories per day.')
elif totalCalories <= maxCaloriesPerDay:
     print('You are', maxCaloriesPerDay - totalCalories, 'calories under your maximum calories per day. ')

试着做:

totalCalories = totalCalories + caloriesPerMeal

或:

totalCalories += caloriesPerMeal

因为说totalCalories += totalCalories + caloriesPerMeal意味着 totalCalories = 2*totalCalories + caloriesPerMeal

相关问题 更多 >

    热门问题