我已经编写了这段代码来执行两个序列:1 - 绘制三角形的递归显示,保持在边界框内,并返回所有绘制区域的总和; 2--迭代重复
我认为存在一个范围问题,因为' sum'不工作但是,我不知道如何让乌龟留在他的盒子里,而不会改变他随机产生的距离和角度。
import turtle
import random
import math
def BOUNDING_BOX():
#creates a bounding box
turtle.up()
turtle.setpos(-200, -200)
turtle.down()
turtle.fd(400)
turtle.left(90)
turtle.fd(400)
turtle.left(90)
turtle.fd(400)
turtle.left(90)
turtle.fd(400)
turtle.left(90)
turtle.up()
turtle.setpos(0, 0)
def arrowRecur(quan, sum):
if quan == 0: # main() blocks negatives
#base case
return sum
else:
#recursive call
curr_sum = drawTri()
turtle.fd(MAX_DISTANCE())
turtle.right(MAX_ANGLE())
sum += curr_sum
arrowRecur(quan - 1, sum)
def arrowIter(quan, sum):
while quan > 0:
curr_sum = drawTri()
turtle.fd(MAX_DISTANCE())
turtle.right(MAX_ANGLE())
sum += curr_sum
quan -= 1
else:
return sum
def main():
#initializes program
sum = 0
quan = int(input("Enter in the quantity of triangles (0-500): "))
if 0 > quan or quan > MAX_FIGURES():
raise ValueError("Invalid Input: Execution Terminated")
else:
turtle.colormode(255)
BOUNDING_BOX()
sum = arrowRecur(quan, sum)
print("Our total painted area is ",sum," units.")
input("Press ENTER to continue to iterative version.")
main()
答案 0 :(得分:1)
如果您可以编写此代码,您应该能够调试它!你为什么不自己调试?对于将来的问题,您应该遵循以下准则: Are there legitimate "fix my code" questions?
具体来说:“到目前为止您已尝试排除问题的故障排除步骤。”
对于总和问题,有两件事:
>>> 1/2
0
所以这一行计算的区域为0:
return ((1/2)*base*height)
并且在递归中,您没有更新sum的值:
arrowRecur(quan - 1, sum)
应该是
sum = arrowRecur(quan - 1, sum)
return sum
要让乌龟留在盒子里,你需要添加更多代码来检查它的坐标是否永远不会超过盒子的边缘。