我在使用Python的CS项目时遇到了问题,每当我认为我已经接近解决问题时,它就无法工作。
我的老师问我们的是显示实际窗口(不在shell中)中点附近的线的中点坐标。到目前为止,这是我的代码:
win = GraphWin("Exercise 8 Page 119", 400,400)
for i in range(1):
p1 = win.getMouse()
p1.draw(win)
p1.setFill("black")
p2 = win.getMouse()
p2.draw(win)
p2.setFill("black")
line = Line(Point(p1.getX(),p1.getY()), Point(p2.getX(), p2.getY()))
line.draw(win)
# midpoint
midpoint = line.getCenter()
midpoint.draw(win)
midpoint.setFill("cyan")
import math
# midpoint math
yMid = p2.getY()+p1.getY()/2
xMid = p2.getX()+p1.getX()/2
# midpoint text
midpointLabel = Text(Point(xMid+0.5, yMid+0.5), "midpoint is: " + "(" + str(xMid) + "," + str(yMid) + ")")
midpointLabel.draw(win)
每当我测试它时,中点会随机出现,或者根本无法看到它。我似乎无法每次都将坐标放在接近实际中点的位置。这些是教师的确切词语"该程序将标记中点,略微偏离线中点的实际位置。"
请帮帮我!谢谢!
答案 0 :(得分:0)
我说问题是一个简单的数学错误:
yMid = p2.getY()+p1.getY()/2
xMid = p2.getX()+p1.getX()/2
应该是:
yMid = (p2.getY() + p1.getY()) / 2
xMid = (p2.getX() + p1.getX()) / 2
完整代码:
from graphics import *
win = GraphWin("Exercise 8 Page 119", 400, 400)
p1 = win.getMouse()
p1.setFill("black")
p1.draw(win)
p2 = win.getMouse()
p2.setFill("black")
p2.draw(win)
line = Line(p1, p2)
line.draw(win)
# midpoint
midpoint = line.getCenter()
midpoint.setFill("cyan")
midpoint.draw(win)
# midpoint math
yMid = (p2.getY() + p1.getY()) / 2
xMid = (p2.getX() + p1.getX()) / 2
# midpoint text
midpointLabel = Text(Point(xMid + 0.5, yMid + 0.5), "midpoint is: ({}, {})".format(xMid, yMid))
midpointLabel.draw(win)
win.getMouse()
win.close()