我想计算python上不同形状的面积

2024-09-24 06:26:15 发布

您现在位置:Python中文网/ 问答频道 /正文

用户输入“圆圈3.5”或“矩形35”或“梯形35 7”(数字由用户决定),并输出区域。下面是代码,但无法运行

s=input("Input the shape and number:")
# for example,
# s="rect:5 3"
# s="cir:3.5"
#s="trapz:3 5 7"
cmd, para=s.split(:)
print(f"{cmd}->{para}")

if cmd == 'cir':
    r = float(para)
    print(f"area={r*r*3.14}")
elif cmd == 'rect':
    sw, sh = int(para.split())
    print(f"area={sw*sh}")
elif cmd == 'trapz':
    ul, bl, h = int(para.split())
    print(f"area={(ul+bl)*h/2}")
else:
    print("wrong input")

谢谢你的评论。我也尝试用另一种方法来解决这个问题。代码是:

s=input("Input the shape and number:").split()

if s[0]=="cir":
    r = float(s[1])
    print(f'area={r*r*math.pi}')
elif s[0]=="rect":
    sw, sh = int(s[1]), int(s[2])
    print(f"area={sw*sh}")
elif s[0]=="trapz":
    ul, bl, h = int(s[1]), int(s[2]), int(s[3])
    print(f'area={(ul+bl)*h/2}')
else:
    print('Wrong input!')

Tags: rectcmdinputshareaswulint
3条回答

您在此处请求输入并将其答案分配给“s”变量:

s=input("Input the shape and number:")

然后将s变量的值更改为不同的字符串三次

s="rect:5:3"
s="cir:3.5"
s="trapz:3 5 7"

在这行代码之后,s变量等于字符串:“trapz:3 5 7”,而不管用户输入什么

此外,用作“split”参数的冒号必须是字符串

您不能只将int应用于列表

s=input("Input the shape and number:")
cmd, para=s.split(":")
print(cmd,"->",para)

if cmd=='cir':
    r = float(para)
    print(f"arear={r*r*3.14}")
elif cmd=='rect':
    sw, sh = (float(x) for x in para.split())
    print(f"area={sw*sh}")
elif cmd=='trapz':
    ul, bl, h = (float(x) for x in para.split())
    print(f"area={(ul+bl)*h/2}")
else:
    print("wrong input")

尝试:

s=input("Input the shape and number:")
s = s.split(':')
cmd, para= s[0], s[1:] # <---- added this
print(cmd,"->",para)

if cmd=='cir':
    r = float(para[0])
    print(f"arear={r*r*3.14}")
elif cmd=='rect':
    sw, sh =list(map(int, para)) #<---- added this
    print(f"area={sw*sh}")
elif cmd=='trapz':
    ul, bl, h = list(map(int, para))
    print(f"area={(ul+bl)*h/2}")
else:
    print("wrong input")

Input the shape and number:trapz:3:5:7
trapz -> ['3', '5', '7']
area=28.0


Input the shape and number:rect:3:5
rect -> ['3', '5']
area=15

Input the shape and number:cir:4.6
cir -> ['4.6']
arear=66.44239999999999

相关问题 更多 >