2017-12-03 323 views
0

所以我完成了程序,据我所知,但我有一个格式问题的def main()函数的最后一个打印语句打印两次,我不明白为什么 - 非常恼人。无论如何,我敢肯定,这是一些简单的我失踪,这里是我的代码:为什么我的python程序最后两次打印语句?

import math 

#---------------------------------------------------- 
# distance(draw,angle) 
# 
# This function computes the distance of the shot 
#---------------------------------------------------- 

def distance(draw,angle): 
    velocity = draw*10 
    x = (angle) 
    sin_deg = math.sin(math.radians(2*x)) 
    g = 32.2 
    dist = (((velocity**2) * sin_deg)/g) 
    return dist 

#---------------------------------------------------- 
# Main Program # 
#---------------------------------------------------- 

dist_to_pig = int(input("Distance to pig (feet) -------- ")) 

def main(): 
    angle_of_elev = float(input("Angle of elevation (degrees) -- ")) 
    draw_length = float(input("Draw length (inches) ---------- ")) 
    print() 
    distance_calc = round(distance(draw_length,angle_of_elev)) 
    short_result = int(round(dist_to_pig - distance_calc)) 
    long_result = int(round(distance_calc - dist_to_pig)) 


    if distance_calc < (dist_to_pig - 2): 
     print("Result of shot ---------------- ", (short_result - 2), "feet too short") 
     print() 
     main() 
    if distance_calc > (dist_to_pig + 2): 
     print("Result of shot ---------------- ", (long_result - 2), "feet too long") 
     print() 
     main() 
    else: 
     print("OINK!") 

#---------------------------------------------------- 
# Execution # 
#---------------------------------------------------- 

main() 

如果你看到我的代码中的任何其他问题,请随时指出这一点。谢谢!

+0

您正在递归调用39号主函数,是故意吗? – csharpcoder

+2

哪一行准确地打印两次?尝试将第二条if语句更改为elif。 –

回答

0

JediObiJohn,OINK是印刷,因为递归多次。更改第二个如果为elif它应该解决您的问题。

+0

这修正了它!这就是我试图使用递归哈哈。谢啦。 – JediObiJohn

0
def main(i): 
    if i < 2: 
     print(i) 
    if i > 2: 
     print(i) 
    else: 
     print("Hello") 

基于这个简单的程序,如果你尝试一些情况:

>>> main(1) 
>>> 1 
Hello 
>>> main(3) 
3 
>>> main(2) 
Hello 

你看到的区别?当第一个IFTRUE时,则第二个将为FALSE,因此ELSE部分将被执行。

0

我想你想的实际是:

if distance_calc < (dist_to_pig - 2): 
    main() 
elif distance_calc > (dist_to_pig - 2): 
    main() 
else: 
    print("OK") 

是吗? 如果您使用2'if',则发生distance_calc < (dist_to_pig -2)时,执行2行代码。 main()print(...)。这就是为什么你可以看到印好'OK'的多少次。

0

你两次调用main()函数,一旦开始执行,一旦你的函数里面

相关问题