【问题标题】:check whether two circle touch each other externally and only at one point检查两个圆是否在外部相互接触并且仅在一个点
【发布时间】:2022-01-25 06:08:11
【问题描述】:

我需要通过使用 Circle 类来确定 c1 和 c2 两个圆是否在外部且仅在一个点上相互接触。 我创建了接触的方法。该方法应该返回一个布尔值,它需要像这样调用 c1.touches(c2)

这个公式检查圆圈是否相互接触或相交formula

这是我的代码

import math

class Circle:

    def __init__(self, x, y, r):
        self.x = x
        self.y = y
        self.r = r

    def touches(self):

        dist_between_centers = math.sqrt((self.c1.x - self.c2.x)^(2 + (self.c1.y - self.c2.y)^2))
        if dist_between_centers == (self.c1.r + self.c2.r):
            print("True")
        elif dist_between_centers > (self.c1.r + self.c2.r):
            print("False")
        else:
            print("False")


c1 = Circle(2,3,12)
c2 = Circle(15, 28, 10)
c1.touches(c2)

但是我遇到了这样的错误,TypeError: touches() 需要 1 个位置参数,但给出了 2 个

【问题讨论】:

  • touches 不带参数(self 类除外),但你用一个来调用它:c1.touches(c2)
  • 当我调用它 c1.touches(c2) 我收到类型错误 c1.touches(c2) TypeError: touches() 需要 1 个位置参数,但给出了 2 个
  • 您粘贴的代码有问题。如果您将touches 称为c1.touches(c2),那么您在touches 中访问self.c1self.c2 是很奇怪的。请仔细查看并修复它。
  • 您应该阅读 self 在类函数中的含义,以及为什么您的 c2 参数实际上是第二个参数。
  • 请注意,由于我们不检查交叉点,因此不需要第二次检查,它会触及或不触及。它可能应该返回 boolean True and False 而不是字符串 "True""False"

标签: python class geometry


【解决方案1】:

好像您在def touches 中混淆了selfc1c2 的用法

您应该将c2 作为参数传递给def touches(circle)。在内部方法中,您应该将第一个圆圈称为self 而不是self.c1,将第二个圆圈称为circle 而不是self.c2

这样的最终代码

import math

class Circle:

    def __init__(self, x, y, r):
        self.x = x
        self.y = y
        self.r = r

    def touches(self, circle):

        dist_between_centers = math.sqrt((self.x - circle.x)^2 + (self.y - circle.y)^2)
        if dist_between_centers == (self.r + circle.r):
            print("True")
        elif dist_between_centers > (self.r + circle.r):
            print("False")
        else:
            print("False")


c1 = Circle(2, 3, 12)
c2 = Circle(15, 28, 10)
c1.touches(c2)   

【讨论】:

  • @Schwern 当然。我试图使代码尽可能与 OP 相似
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-02
  • 1970-01-01
  • 2021-09-12
  • 2021-03-14
  • 2015-01-06
相关资源
最近更新 更多