所以我已经完成了程序,据我所知,但我有格式化问题,def main()
函数中的最后一个打印语句打印两次,我无法弄清楚为什么 - 非常烦人。无论如何,我确信这是一件我想念的简单事情,这是我的代码:
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 :(得分: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
你看到了区别吗?当第一个IF
为TRUE
时,则为第二个IF
FALSE
将为ELSE
,因此{{1}}部分将被执行。
答案 1 :(得分:0)
我认为你真正想要的是:
if distance_calc < (dist_to_pig - 2):
main()
elif distance_calc > (dist_to_pig - 2):
main()
else:
print("OK")
我是对的吗?
如果你使用2'如果是,那么当distance_calc < (dist_to_pig -2)
发生时,执行2行代码。 main()
和print(...)
。这就是为什么你可以看到打印出“OK”的多个时间。
答案 2 :(得分:0)
您正在调用main()函数两次,一次开始执行,一次调用函数
答案 3 :(得分:0)
JediObiJohn,OINK由于递归而多次打印。将第二个if更改为 elif ,它应该可以解决您的问题。