CS50课程Half练习题求解:账单拆分计算功能异常排查
问题分析与修复方案
核心错误点
- 整数除法导致小费比例丢失:
在main函数中,tip_percent是整数类型,执行int tip = tip_percent / 100;时,20/100会触发整数除法,结果直接取整为0,导致后续小费计算完全错误。 - 函数参数类型不匹配:
half函数的tip参数被定义为int,即便传入正确的浮点比例,也会被强制转换为整数,进一步破坏计算逻辑。
修复后的代码
#include <cs50.h> #include <stdio.h> float half(float bill, float tax, float tip); int main(void) { float bill_amount = get_float("Bill before tax and tip: "); float tax_percent = get_float("Sale Tax Percent: "); int tip_percent = get_int("Tip percent: "); // 修正:将小费比例转为浮点类型,使用浮点除法 float tax = tax_percent / 100.0; float tip = tip_percent / 100.0; printf("You will owe $%.2f each!\n", half(bill_amount, tax, tip)); } // 修正:将tip参数改为float类型 float half(float bill, float tax, float tip) { float bill_after_tax = bill * (1 + tax); float total = bill_after_tax * (1 + tip); return total / 2; }
修复说明
- 把
main里的tip变量类型改为float,并且用100.0做除数触发浮点除法,确保比例计算准确(比如20/100.0得到0.2)。 - 修改
half函数的tip参数类型为float,避免整数转换导致的精度丢失。 - 简化计算逻辑:
bill * (1 + tax)等价于bill + bill*tax,bill_after_tax * (1 + tip)等价于bill_after_tax + bill_after_tax*tip,写法更简洁。
测试示例输入时,计算过程如下:
- 税前账单12.50,税率8.875% → 税后金额:12.50 * (1 + 0.08875) = 13.609375
- 加上20%小费 → 总金额:13.609375 * (1 + 0.2) = 16.33125
- 拆分两半 → 16.33125 / 2 = 8.165625,格式化后显示为$8.17,符合示例输出。
内容的提问来源于stack exchange,提问作者Andressa
相关产品推荐
相关产品推荐

