2017-12-03 328 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()函數,一旦開始執行,一旦你的函數裏面

相關問題