首页 > 解决方案 > 如何分离这些输入并仍然使它们成为浮点数?

问题描述

三角形可以根据其边长分类为等边、等腰或不等边。等边三角形的所有 3 条边都具有相同的长度。等腰三角形有两条边长度相同,第三条边长度不同。如果所有边的长度不同,则三角形是不等边的。编写一个程序,从用户那里读取三角形 3 条边的长度。显示指示三角形类型的消息

这是我的代码,它不起作用:

    #this code doesn't work for some reason: 
s1, s2, s3 = float(input('Enter three sides (separated by comma): ').split(','))
    
    if s1 == s2 and s2 == s3:
        print('Equilateral')
    elif (s1 == s2 and s2 != s3) or (s1 == s3 and s2 != s3) or (s2 == s3 and s1 != s2):
        print('Isosceles')
    else:
        print('Scalene')

我错过了什么?

标签: pythonsplittriangle

解决方案


这看起来像您正在尝试将字符串列表转换为浮点列表。这不起作用。

我会使用这样的东西:

str1, str2, str3 = input('Enter three sides (separated by comma): ').split(',')
s1 = float(str1)
s2 = float(str2)
s3 = float(str3)

或列表理解:

s1, s2, s3 = [float(s) for s in input('Enter three sides (separated by comma): ').split(',')]

推荐阅读