我已经编写了以下代码,但是我无法确定它是否识别出等边三角形,因为我无法输入我需要的坐标(3的平方根,示例):
x1 = eval(input('x1: '))
y1 = eval(input('y1: '))
x2 = eval(input('x2: '))
y2 = eval(input('y2: '))
x3 = eval(input('x3: '))
y3 = eval(input('y3: '))
side1 = (abs(x1 - x2) + abs(y1 - y2)) ** (1/2)
side2 = (abs(x2 - x3) + abs(y2 - y3)) ** (1/2)
side3 = (abs(x3 - x1) + abs(y3 - y2)) ** (1/2)
print('side1: ', side1, 'side2: ', side2,'side3:', side3)
if side1 + side2 > side3 and side2 + side3 > side1 and side1 + side3 > side2 :
if side1 == side2 == side3:
print('This triangle is equilateral')
elif side1 == side2 or side2 == side3 or side1 == side3 :
print('This triangle is isosceles')
else:
print('This triangle is scalene')
else:
print('This is not a triangle!')
编辑:我已经重写了以下代码
x1 = eval(input('x1: '))
y1 = eval(input('y1: '))
x2 = eval(input('x2: '))
y2 = eval(input('y2: '))
x3 = eval(input('x3: '))
y3 = eval(input('y3: '))
side1 = ((x1 - x2)**2 + (y1 - y2)**2) ** (1/2)
side2 = ((x2 - x3)**2 + (y2 - y3)**2) ** (1/2)
side3 = ((x3 - x1)**2 + (y3 - y1)**2) ** (1/2)
print('side1: ', side1, 'side2: ', side2,'side3:', side3)
if side1 + side2 > side3 and side2 + side3 > side1 and side1 + side3 > side2 :
if side1 == side2 == side3:
print('This triangle is equilateral')
elif side1 == side2 or side2 == side3 or side1 == side3 :
print('This triangle is isosceles')
else:
print('This triangle is scalene')
else:
print('This is not a triangle!')
答案 0 :(得分:2)
更新的代码:
from math import sqrt
x1 = float(raw_input('x1: '))
y1 = float(raw_input('y1: '))
x2 = float(raw_input('x2: '))
y2 = float(raw_input('y2: '))
x3 = float(raw_input('x3: '))
y3 = float(raw_input('y3: '))
side1 = sqrt((x1 - x2)**2 + (y1-y2)**2)
side2 = sqrt((x2 - x3)**2 + (y2-y3)**2)
side3 = sqrt((x3 - x1)**2 + (y3-y1)**2)
# Put the sides into a list; sort them.
tri= [side1, side2, side3]
tri.sort()
if tri[0] < tri[1]+tri[2]:
if tri[0] == tri[2]:
print('This triangle is equilateral')
elif tri[1] == tri[2] or tri[1] == tri[0]:
print('This triangle is isosceles')
else:
print('This triangle is scalene')
else:
print('This is not a triangle!')
答案 1 :(得分:1)
听起来问题实际上是关于如何输入输入。您需要将输入包装在引号中,因为eval
需要字符串输入,而不是数字类型。
eval
函数将该字符串解析为Python代码。因此,您使用与代码中相同的平方根语法。
例如,让我们测试一个等边三角形。我从终端运行您的(编辑过的)脚本,并输入坐标作为字符串。
x1: '0'
y1: '0'
x2: '2'
y2: '12**0.5'
x3: '4'
y3: '0'
('side1: ', 1.0, 'side2: ', 1.0, 'side3:', 1.0)
This triangle is equilateral