测试预期值与输出值一致但测试失败,求pyramid_volume函数排查方案
问题解决方法
你的代码核心问题是函数返回值类型不符:
- 测试用例期望返回浮点数值(比如示例中的
9.45是float类型),但你的函数返回的是格式化后的字符串(比如"9.45")。即使内容一致,类型不匹配会导致测试断言失败。
修改后的代码
def pyramid_volume(base_length, base_width, pyramid_height): base_area = base_length * base_width volume = (base_area * pyramid_height) / 3 return volume # 直接返回计算得到的浮点数值 length = float(input()) # I cannot change from here down width = float(input()) height = float(input()) print('Volume for 4.5, 2.1, 3.0 is:', pyramid_volume(length, width, height))
补充说明
如果需要避免浮点精度导致的类似9.450000000000001的问题,可以用round()函数确保返回值保留两位小数:
return round(volume, 2)
内容的提问来源于stack exchange,提问作者putput
相关产品推荐
相关产品推荐

