首页 > 解决方案 > 我一直尝试在 Python 上运行这个程序,但我一直收到相同的操作数错误。错误代码来自第 10 行

问题描述

此代码对我不起作用,并且我不断收到不受支持的操作数类型错误。错误代码读取 TypeError: unsupported operand type(s) for Sub: 'str' and 'str' on line 10

x1 = input(print("What is the x coordinate of the first circle: "))
y1 = input(print("What is the y coordinate of the first circle: "))
r1 = input(print("What is the radius of the first circle: " ))
x2 = input(print("What is the x coordinate of the second circle: "))
y2 = input(print("What is the y coordinate of the second circle: "))
r2 = input(print("What is the radius of the second circle: "))

import math
def distance(x1, y1, x2, y2):
    return math.sqrt(math.pow(x2 - x1, 2) +
            math.pow(y2 - y1, 2) * 1.0) 
print("%.6f"%distance(x1, y1, x2, y2)) 

if distance <= abs(r1 - r2):
    print("Circle 2 is inside of circle 1")
elif distance <= r1 + r2:
    print("Circle 2 overlaps circle 1")
else:
    print("Circle 2 does not overlap circle 1")

标签: pythonpython-3.xpython-2.7listpython-requests

解决方案


输入接收一个字符串。您需要将其转换为数字格式。请检查如何将字符串解析为浮点数或整数?

此外,当您进行比较时,您必须使用参数调用该函数。我没有检查数学,但我想这就是你要找的:

y1 = float(input(print("What is the y coordinate of the first circle: ")))
r1 = float(input(print("What is the radius of the first circle: " )))
x2 = float(input(print("What is the x coordinate of the second circle: ")))
y2 = float(input(print("What is the y coordinate of the second circle: ")))
r2 = float(input(print("What is the radius of the second circle: ")))

import math
def distance(x1, y1, x2, y2):
    return math.sqrt(math.pow(x2 - x1, 2) +
            math.pow(y2 - y1, 2) * 1.0)
print("%.6f"%distance(x1, y1, x2, y2))

if distance(x1, y1, x2, y2) <= abs(r1 - r2):
    print("Circle 2 is inside of circle 1")
elif distance(x1, y1, x2, y2) <= (r1 + r2):
    print("Circle 2 overlaps circle 1")
else:
    print("Circle 2 does not overlap circle 1")

推荐阅读