【发布时间】:2014-11-09 04:28:48
【问题描述】:
我目前在分配作业时遇到了问题,并且我已经尝试查明我的错误好几个小时了。
我有一个圆形和一个矩形(均由用户点击绘制)。如图所示:
i.stack.imgur (dot) com/4aXIw.png
使用矩形的中心点,我想计算一个位于圆上的新中心点(对于矩形)。我通过计算角度(θ)并使用三角函数来获得新的中心点来实现这一点。
i.stack.imgur (dot) com/NoCBS.png
但是,当我运行我的程序时,我没有得到正确的结果。此处显示:
i.stack.imgur (dot) com/ZG9Ld.png
我已经检查了一百次,但我似乎无法确定我在哪里搞砸了。我检查了theta,得到的度数是正确的。这是相关代码,我怀疑我犯了错误:
theta = math.atan((initialrec_y-click1.y)/(initialrec_x-click1.x))
theta = int(math.degrees(theta))
rec_x = click1.x + radius*math.cos(theta)
rec_y = click1.y + radius*math.sin(theta)
如果你想运行它,这里是完整的代码:
from graphics import *
import math
def main():
#setup window
win = GraphWin("Traveling Rectangle",600,450)
win.setCoords(0,0,600,450)
click1 = win.getMouse()
click2 = win.getMouse()
radius = click2.x - click1.x
circle = Circle(click1, radius)
circle.draw(win)
click3 = win.getMouse()
click4 = win.getMouse()
rect = Rectangle(click3, click4)
rect.draw(win)
rect.setFill("red")
rect.setOutline("red")
#the centerpoint of the initial rectangle
initialrec_x = (click3.x + click4.x) / 2
initialrec_y = (click3.y + click4.y) / 2
#the trig to calculate the point on the circle
theta = math.atan((initialrec_y-click1.y)/(initialrec_x-click1.x))
theta = int(math.degrees(theta))
#the new centerpoint values of x and y
rec_x = click1.x + radius*math.cos(theta)
rec_y = click1.y + radius*math.sin(theta)
main()
我们将不胜感激!
抱歉,该网站不允许我发布图片。图形库可以在这里找到:mcsp.wartburg (dot) edu/zelle/python/graphics.py
【问题讨论】:
-
我没有看到任何改变矩形坐标或重绘它的东西。
-
math.cos()和math.sin()想要以弧度而不是度数为单位的参数。此外,math.atan()不太可能在上象限之外工作。相反,您可能想要math.atan2()。
标签: python python-3.x trigonometry