Python计算几何体的表面积和体积

img


作为初级学生,这个Python题有点难,任务说还要判断二维和三维的形状,再算其面积和体积,可以方便告诉我吗?真的很感谢!

我给你写了一版,供你参考。如果对你有帮助,望采纳

import math


def square(length, width):
    return length * width, 0


def cube(length, width, height):
    s = (length * width + length * height + width * height) * 2
    v = length * width * height
    return s, v


def circle(radius):
    return math.pi * radius ** 2, 0


def sphere(radius):
    s = 4 * math.pi * radius ** 2
    v = 4 * math.pi * radius ** 3 / 3
    return s, v


def cylinder(radius, height):
    s = 2 * circle(radius) + 2 * math.pi * radius * height
    v = circle(radius) * height
    return s, v


def cone(radius, height):
    s = circle(radius) + math.pi * radius * math.sqrt(radius ** 2 + height ** 2)
    v = circle(radius) * height / 3
    return s, v


def tri_prism(side, height):
    s = side * height * 3 + math.sqrt(3) * side ** 2
    v = math.sqrt(3) * side ** 2 / 2 * height
    return s, v


def type_judge(geom_type):
    if geom_type == '长方形':
        length, width = map(float, input().split())
        return square(length, width)
    elif geom_type == '长方体':
        length, width, height = map(float, input().split())
        return cube(length, width, height)
    elif geom_type == '圆形':
        radius = float(input())
        return circle(radius)
    elif geom_type == '球':
        radius = float(input())
        return sphere(radius)
    elif geom_type == '圆柱体':
        radius, height = map(float, input().split())
        return cylinder(radius, height)
    elif geom_type == '圆锥':
        radius, height = map(float, input().split())
        return cone(radius, height)
    elif geom_type == '正三棱柱':
        side, height = map(float, input().split())
        return tri_prism(side, height)


def main():
    geom_type = input()
    s, v = type_judge(geom_type)
    if v:
        print("%.2f %.2f" % (s, v))
    else:
        print("%.2f" % s)


if __name__ == "__main__":
    main()