繁体   English   中英

TypeError:/:'float'和'str'不支持的操作数类型[重复]

[英]TypeError: unsupported operand type(s) for /: 'float' and 'str' [duplicate]

我正在尝试根据长度和边数计算面积。 我想根据形状输入将形状编号设置为 3、4 等; 本质上是将字符串转换为 int 并在方程式中使用它。 有人可以解释为什么会发生这个错误吗?

import math

shape1 = input('What is your first shape? ')
length1 = input("What is the length of its side?")
shape2 = input("What is your second shape?")
length2 = input("What is the length of its side?")

#Equate shape1 to side number
if shape1 == 'triangle' or 'Triangle':
    shape1 == int(3)
elif shape1 == 'square' or 'Square':
    shape1 == int(4)
elif shape1 == 'pentagon' or 'Pentagon':
    shape1 == int(5)
elif shape1 == 'hexagon' or 'Hexagon':
    shape1 == int(6)
#Equate shape2 to side number
if shape2 == 'triangle' or 'Triangle':
    shape2 == int(3)
elif shape2 == 'square' or 'Square':
    shape2 == int(4)
elif shape2 == 'pentagon' or 'Pentagon':
    shape2 == int(5)
elif shape2 == 'hexagon' or 'Hexagon':
    shape2 == int(6)
#Calculate area of shape 1
apothem1 = ((0.5*int(length1))/math.tan(3.141593/(shape1)))
perimeter1 = (int(shape1)*int(length1))
area1 = (int(sides1)*int(length1)*int(apothem1))
#Calculate perimeter of shape 1
perimeter1 = (sides1*length1)
#Calculate area of shape 2
aapothem2 = ((0.5*int(length2))/math.tan(3.141593/(shape2)))
perimeter2 = (int(shape2)*int(length2))
area2 = (int(sides2)*int(length2)*int(apothem2))
#Calculate perimeter of shape 2
perimeter2 = (sides2*length2)
#Compare area values
if int(area1) > int(area2):
    print("Polygon 1's perimeter is larger")
    print(int(area1), int(area2))
elif area1 == area2:
    print("The perimeters are equal")
    print(int(area1), int(area2))
else:
    print ("Polygon 2's perimeter is larger")
    print(int(area1), int(area2))
#Compare perimeter values
if int(perimeter1) > int(perimeter2):
    print("Polygon 1's perimeter is larger")
    print(int(perimeter1), int(perimeter2))
elif int(perimeter1) == int(perimeter2):
    print("The perimeters are equal")
    print(int(perimeter1), int(perimeter2))
else:
    print ("Polygon 2's perimeter is larger")
    print(int(perimeter1), int(perimeter2))

更改变量时不应使用 ==。 您的陈述应类似于:

if shape1 == 'triangle' or 'Triangle':
    shape1 = int(3)

您还重新声明了边界 1 和 2 两次,因此您可以考虑为它们分配新变量。 apothem2 被声明为 aapothem2,而 shape1 似乎在某个时候变成了 side1。

integer 是没有小数的正数或负数,而浮点数都是实数。 在你有方法int([variable])的地方,你要求程序将浮点数除以 integer,这会给你一个错误。 尝试用 float([variable]) 替换int([variable]) float([variable])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM