2013-05-31 42 views
0

我在做一个宏量营养素计算器。如果用户使错误计算器重新启动并返回到main(),则此计算器。不过,我相信我使用的main()在我的代码导致2所重新启动到主要功能

这里运行的显示是链接到我的代码:http://pastebin.com/FMqf2aRS

*******Welcome to the MACRONUTRIENT CALCULATOR******** 
    Enter your calorie deficit: 30 
    Percentage of Protein: 30 
    Percent of Carbohydrates: 40 
    Percentage of Fats: 40 
    Total percentages surpassed 100! Please reenter percentages. 
    *******Welcome to the MACRONUTRIENT CALCULATOR******** 
    Enter your calorie deficit: 2200 
    Percentage of Protein: 30 
    Percent of Carbohydrates: 30 
    Percentage of Fats: 40 
    You must eat 660.0 calories of protein which is equivalent to 165.0 grams of protein. 
    You must eat 880.0 calories of fat which is equivalent to 97.7777777778 grams of fat. 
    You must eat 660.0 calories of carbohydrates which is equivalent to 73.3333333333 grams of carbohydrates. 
    You must eat 9.0 calories of protein which is equivalent to 2.25 grams of protein. 
    You must eat 12.0 calories of fat which is equivalent to 1.33333333333 grams of fat. 
    You must eat 12.0 calories of carbohydrates which is equivalent to 1.33333333333 grams of carbohydrates. 

有接近此不同的方式防止这种情况发生?

+0

当然,不是要回'main',回到某个地方,只是做了计算。你可以通过从'main'中取出所有'输入'和计算等操作并将其放入一个名为'run'的函数来完成此操作。然后'main'在打印欢迎信息后调用'run()',如果你需要再次尝试,你可以再次调用'run'。 –

回答

2

打电话给main()你这样做的方式是解决这个问题的错误方法。您正在将越来越多的main()调用推入堆栈 - 如果您连续多次输入无效的条目,程序最终会崩溃。您应该使用while循环如下图所示

def main(): 
    while True: 
     print "*******Welcome to the MACRONUTRIENT CALCULATOR********" 
     calorie_deficit = float(input("Enter your calorie deficit: ")) 
     Percent_protein = float(input("Percentage of Protein: ")) 
     Percent_carb = float(input("Percent of Carbohydrates: ")) 
     Percent_fat = float(input("Percentage of Fats: ")) 
     Macro_dict = {'Protein': Percent_protein, 'Carbohydrate': Percent_carb, 'Fats': Percent_fat} 
     Macro_sum = Percent_protein + Percent_carb + Percent_fat 
     if not Total_Macro_Check(Macro_sum): 
      continue 
     Macro_percentage_to_calorie(calorie_deficit, Percent_protein, Percent_carb, Percent_fat) 


def Total_Macro_Check(total_val): 
    if total_val > 100: 
    print "Total percentages surpassed 100! Please reenter percentages." 
    return False 
    if total_val < 100: 
    print "Total precentages is less than 100! Please reenter precentages." 
    return False 
    return True 
+1

默认的递归限制是1000.你需要吃很多才能达到此目的。 ;) –

+0

感谢您的帮助gnibbler! – Liondancer

+1

@MikeMüller,这是错过了重点。以递归方式调用main()不是意图,所以这是一个错误。大部分时间不显示的错误可能很难追查到。 –

1

的代码是做你告诉它到底是什么做的:

def Total_Macro_Check(total_val): 
    if total_val > 100: 
    print "Total percentages surpassed 100! Please reenter percentages." 
    main() 
    if total_val < 100: 
    print "Total precentages is less than 100! Please reenter precentages." 
    main() 

你再打电话为主。