Python分支语句计算正方形、六边形面积周长输出错误求助
问题原因
- 核心错误:判断语句逻辑永远为真,所有输入都会走到圆形计算分支
你写的shape == "circle" or "Circle"的执行逻辑是:先计算shape == "circle"的结果,如果为假,会继续计算bool("Circle"),而非空字符串的布尔值恒为真,所以整个判断永远返回True。你输入正方形、六边形时,都会触发第一个if分支,把输入的边长当成圆的半径计算,自然结果不符合预期。你给出的正方形边长3.75的实际输出,正好对应半径3.75的圆的面积和周长,也验证了这个问题。 - 次要错误:正方形、六边形的计算公式本身存在错误
- 正方形周长公式错误:你写的
perimSquare = 4 * areaSquare,正确逻辑是4乘以边长,而非乘以面积 - 正六边形面积公式错误:你写的
math.pi(3)是错误写法,公式里需要的是根号3,对应语法是math.sqrt(3),pi是圆周率常量,没有调用传参的用法 - 正六边形周长公式错误:你写的
perimHex = 6 * areaHex,正确逻辑是6乘以边长,而非乘以面积
- 正方形周长公式错误:你写的
- 优化点:圆形分支的输入变量名是circumf(本意是周长),但计算时实际当作半径使用,容易引发后续混淆,建议调整变量名。
修复后代码
import math # 提前获取形状输入,统一转小写后无需额外判断大小写 shape = input("Please enter the shape(circle/square/hexagon): ").lower() if shape == "circle": radius = float(input("Please provide the radius: ")) area_circle = math.pi * radius ** 2 perim_circle = 2 * math.pi * radius print("{:^14}{:^14}{:^14}{:^14}".format("Shape", "Value", "Area", "Perimeter")) print("{:^14}{:^14.2f}{:^14.2f}{:^14.2f}".format(shape, radius, area_circle, perim_circle)) elif shape == "square": side_square = float(input("Please provide the side length: ")) area_square = side_square ** 2 perim_square = 4 * side_square print("{:^14}{:^14}{:^14}{:^14}".format("Shape", "Value", "Area", "Perimeter")) print("{:^14}{:^14.2f}{:^14.2f}{:^14.2f}".format(shape, side_square, area_square, perim_square)) elif shape == "hexagon": side_hex = float(input("Please provide the side length: ")) area_hex = (3 * math.sqrt(3) * side_hex ** 2) / 2 perim_hex = 6 * side_hex print("{:^14}{:^14}{:^14}{:^14}".format("Shape", "Value", "Area", "Perimeter")) print("{:^14}{:^14.2f}{:^14.2f}{:^14.2f}".format(shape, side_hex, area_hex, perim_hex)) else: print("I don't have the formulas for a {}.".format(shape))
修复后输入正方形边长3.75,输出为面积14.06、周长15.00,和预期一致。
内容的提问来源于stack exchange,提问作者user16188627
相关产品推荐
相关产品推荐

