计数器未按所需数量递增

问题描述 投票:0回答:1

我正在用Python编写一段代码,计算用户所需的卡路里量以及他们每天需要吃多少一种特定食物以确保满足他们的卡路里需求。为此,我创建了一个存储不同键的字典哪些是食物,哪些是食物的卡路里含量。我已经包含了一个随机生成器,因此它会从字典中随机选择一种食物(通过转换为列表),并且这部分工作正常。选择食物后,while 循环开始。假设随机生成的食物的卡路里为 300 卡路里,而用户需要 1200 卡路里。 while 循环将确保在随机生成的食物等于用户所需的卡路里之前,随机生成的食物的卡路里不断添加到单独的变量中,直到该变量等于用户所需的卡路里量。用户。当这种情况发生时,每当需要另一份食物时,就会有另一个计数器递增。 让我们回到这个例子。食物(例如香蕉)提供 300 卡路里,但用户需要 1200 卡路里。因为 300 小于 1200,所以有一个变量我们称之为 CURRENT_CALORIES,它将所有 300 相加,以便稍后与 1200 进行比较,并存储此值里面有300个。现在它已经存储了这 300 个卡路里,一个名为 amount 的变量正在跟踪需要多少香蕉才能满足用户的卡路里需求,因此当需要另外 300 卡路里(1 个香蕉)时,它会将计数器增加 1。

我的问题是,显示了所需卡路里的正确数量,但提供这些卡路里所需的食物量始终只显示一。例如,在我的一次测试中,有人需要 1600 卡路里的热量,而麦片粥碗则需要 110 卡路里。显然,我大约需要 16 个碗,但它说我需要 0 个碗。


def calories():
    print()
    print("C A L O R I E   C A L C U L A T O R")
    print()
    global calorie
    calorie = 0
    
    def male():
        BMR = 88.362+(13.397*weight)+(4.799*height)-(5.677*age)
        calorie = BMR*activity
        print("Your calorie requirements are ", calorie, "kcal")
        print("the total calories you need per day is ", calorie)

    
    def female():
        BMR = 447.593+(9.247*weight)+(3.098*height)-(4.330*age)
        calorie =BMR*activity
        calorie = round(calorie,-2)
        print("the total calories you need per day is ", calorie)

        
    gender= input("Enter your gender, male or female: ")
    weight = int(input("Enter your weight, in kg: "))
    height = int(input("Enter your height, in cm: "))
    age= int(input("Enter your age: "))
    print()
    activitylevel = int(input("""Enter the numbers corresponding to each level
Is your activity level:
1 - Little or no excercise
2 - Light excercise or sports 1-3 days a week
3 - Moderately active or sports 3 - 5 days a week
4 - Very active 6 - 7 days a week
5 - Super active very hard excercise, physical job

-> """))
    activity = [1.2, 1.375, 1.55, 1.725, 1.9]
    activity = activity[activitylevel-1]
    if gender == 'female':
        female()
    elif gender == 'male':
        male()
    print()
    
    calorie = round(calorie,-1)
    food = {"breads":30, "apples":90, "bananas":110,
            "bowl of cheerios":110, " lamb ribs":170,
            "hazelnuts":80}
    random_key = random.choice(list(food.keys()))
    random_value = food[random_key]
    total = 0
    amount = 0
    while total<calorie:
        total += random_value
        amount+= 1
    print()
    print("Thats about the same as ", amount, random_key)
    
calories()  

这是代码。我根本不知道该怎么办,因为我找不到任何东西。我完全迷路了。我知道我必须亲自尝试,但我真的不知道,一切对我来说似乎都是正确的。 问题可能出在 while 循环中的某个地方,并且它没有正确递增。我确实尝试做 amount = amount+1 即使它是同一件事只是为了确保,但这对以太没有影响。请有人帮忙。我希望您只更改不正确或有问题的代码区域,而不是将整个代码更改为您认为更简单的代码。我知道我的可能会更长,但我真的希望它保持这种状态。 非常感谢您的帮助。

python counter
1个回答
0
投票

代码写得很奇怪。无论如何,您在

calorie
male
函数中计算的
female
值不会从这些函数中返回,因此您要比较的
calorie
仍设置为 0,并且
while total<calorie:
永远不会
True
.

© www.soinside.com 2019 - 2024. All rights reserved.