You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python入门:长方体计算器面积体积取整错误及首个制表符不显示问题

长方体计算器程序问题解决

问题描述

我学习Python第一周写了个长方体计算器,碰到两个问题:

  1. 计算出的面积和体积没法正确四舍五入;
  2. 最后一行输出里第一个制表符不显示,只有第二个正常。
    试过把变量设成float类型,问题还是没解决,不知道哪里错了。程序代码如下:
# 从math模块导入平方根函数
from math import sqrt

print("Cuboid Calculator")

print()

# 输入部分
# 获取用户输入的宽、长、高
w = float(input("Enter the width (cm): "))
l = float(input("Enter the length (cm): "))
h = float(input("Enter the height (cm): "))

print()

# 计算部分
# 计算长方体的表面积、体积和体对角线
area = 2*(l*w + l*h + w*h)
volume = l*w*h
diagonal = sqrt(l**2 + w**2 + h**2)

print()

# 输出部分
print("Area of the cuboid is", round(area, 4), "square cm")
print("Space diagonal of the cuboid is", round(diagonal, 3), "cm")
print("Volume of the cuboid is", round(volume, 2), "cubic cm")

print()

print("**Cuboid dimensions**")
# 输出保留1位小数的宽、长、高,中间用制表符分隔
print("width =", round(w,1), "cm" + '\t' + "length = ", round(l,1), "cm" + '\t' + "height =", round(h,1), "cm")

问题1:四舍五入无效的解决

你遇到的不是round()函数失效,而是浮点数的二进制精度问题。比如有些十进制小数(像0.1)在二进制里是无限循环的,计算后会产生微小误差,导致round()后的结果看起来不符合预期。

解决方法有两种:

  • 用字符串格式化输出,既完成四舍五入又确保显示正确:
    print(f"Area of the cuboid is {area:.4f} square cm")
    print(f"Space diagonal of the cuboid is {diagonal:.3f} cm")
    print(f"Volume of the cuboid is {volume:.2f} cubic cm")
    
    这种方式直接控制显示的小数位数,比单独用round()更直观。
  • 如果需要精确计算(比如涉及财务场景),用decimal模块处理浮点数:
    from decimal import Decimal, getcontext
    getcontext().prec = 10  # 设置精度
    
    w = Decimal(input("Enter the width (cm): "))
    l = Decimal(input("Enter the length (cm): "))
    h = Decimal(input("Enter the height (cm): "))
    
    area = 2*(l*w + l*h + w*h)
    volume = l*w*h
    diagonal = (l**2 + w**2 + h**2).sqrt()
    
    print(f"Area of the cuboid is {area:.4f} square cm")
    

问题2:制表符不显示的解决

原代码里print()的多个参数默认用空格分隔,导致你拼接的"cm\tlength = "前面会多出一个空格(因为round(w,1)和这个字符串之间是print自动加的空格),看起来像制表符没生效。

直接用f-string重构最后一行输出,把所有内容整合到一个字符串里,避免自动空格的干扰:

print(f"width = {round(w,1)} cm\tlength = {round(l,1)} cm\theight = {round(h,1)} cm")

这样制表符的位置完全由你控制,不会被print的默认空格打乱。

内容的提问来源于stack exchange,提问作者BoyWonder16

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 08:13:15