我有以下代码,每次都应打印一条消息:
if pitch > 0 and pitch < 180 :
print "forward"
if pitch > -180 and pitch < 0 :
print "backward"
if yaw < 0 and yaw > -180 :
print "left"
if yaw < 180 and yaw > 0 :
print "right"
if (yaw == yawN )and (pitch == pitchN) :
print "stable"
我得到的是一次两条消息
forward
left
forward
left
forward
left
我每次都能做一条消息吗?
答案 0 :(得分:1)
您将收到yaw
的一条消息和pitch
的一条消息,因为您没有采取任何措施阻止这种情况发生,您可以通过简单地替换您的消息来打印一条消息if
个elif
s,如下:
if pitch > 0 and pitch < 180 :
print "forward"
elif pitch > -180 and pitch < 0 :
print "backward"
elif yaw < 0 and yaw > -180 :
print "left"
elif yaw < 180 and yaw > 0 :
print "right"
else :
print "stable"
然而,这不可能做你想要的,因为你真的想要一个1度的俯仰角和175度的偏航角并报告为&#34;前进&#34;?相反,您可能希望比较值的大小(abs(pitch)
将返回幅度),然后将响应基于具有更高幅度的值,如下所示:
if pitch == 0 and yaw == 0 :
# Eliminate the stable option first to cut down on comparisons
print("stable")
elif abs(pitch) > abs(yaw) :
# If we're pitching more than yawing, only give the pitch message
if pitch > 0 :
print "forward"
else :
print "backward"
else :
# The other options have been eliminated, so we must be yawing more than pitching
if yaw < 0 :
print "left"
else :
print "right"
(我已经假设你在-180 < theta <= 180
范围内维持你的角度;如果没有,你应该这样做)
虽然您可能还需要一组混合消息,以便在两个方向上都有重要输入时,如果偏航为90且音高为90,则报告类似&#34;前向右&#34;
答案 1 :(得分:1)
我们可以使用if-elif获得所需的输出,如下所示:
if pitch > 0 and pitch < 180 :
print "forward"
elif pitch > -180 and pitch < 0 :
print "backward"
elif yaw < 0 and yaw > -180 :
print "left"
elif yaw < 180 and yaw > 0 :
print "right"
elif (yaw == yawN )and (pitch == pitchN) :
print "stable"
else:
print "default"
看看这是否有帮助!
答案 2 :(得分:0)
那是因为它可以前进和左(例如)。所以你总会得到两条消息。