【发布时间】:2016-06-02 17:22:28
【问题描述】:
这是我关于通过类创建几何形状的第二个问题。
所以,我想创建一个圈子。
- 首先我创建了一个Point类
- 然后 - 创建一个 Line 类,使用两个点(这将是我们的直径)
- 现在我们必须计算这些点之间的距离(直径)
- 然后我们创建类 Circle
- 并使用直径创建一个圆
希望,到目前为止一切顺利。但是当我开始编码时,我遇到了一些麻烦。
创建类点:
class Point
attr_accessor :x, :y
def initialize
@x = 10
@y = 10
end
end
然后,线类:
class Line
attr_accessor :p1, :p2
def initialize
@p1 = Point.new
@p2 = Point.new
end
def distance
@distance = Math::sqrt((@p2.x - @p1.x) ** 2 + (@p2.y - @p1.y) ** 2) # -> rb.16
end
end
在 Line 类中问题开始了。如您所知,我想定义方法来计算 Line 类中点之间的距离。 Thnx to google search 计算公式为:
((point_2.x - point_1.x)**2 + (point_2.y - point_1.y)**2) 的平方根
#points
point_01 = Point.new
point_01.x = 20
point_02 = Point.new
point_02.x = 10
#line
d = Line.new
d.p1 = point_01
d.p2 = point_02
dis = d.distance # -> rb.40
print dis
但它给我一个错误:
rb:16:in `distance': wrong number of arguments (1 for 0) (ArgumentError)
rb:40: in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
这是什么错误,它们是什么意思?
下一步将使用公式计算周长(C):
C = Pi * 直径
是吗?
class Circle
attr_accessor :diametr, :c
def initialize
@diametr = Line.new
end
def circle_length
return @c = @diametr * Math::PI
end
end
#circle
circle = Circle.new
circle.diametr = d
res = circle.circle_length
请注意,我只是在学习,这可能是一个愚蠢的问题,但我仍然不明白。
感谢您的帮助!
是的,谢谢下面的评论,在使用公式计算周长后,出现错误 Circle 类。你能帮我解决这个问题吗?
【问题讨论】:
-
我运行了您的代码,但没有收到
rb:16:in distance': wrong number of arguments (1 for 0) (ArgumentError)错误。 -
为什么除了中心点和半径之外还需要其他任何东西来识别圆?
-
@Keith Bennett 以及我们如何创建一个没有半径的圆?
-
是不是你从一条线开始,你必须创建一个以它为直径的圆?
-
@AndreyDrozdov 我不明白。我建议可以通过圆心和半径来识别圆。
标签: ruby error-handling geometry shapes