CS50 Half练习题计算错误求助:均分账单结果不符
问题分析与修复:平分账单计算错误
你的代码核心问题是复用了int类型的tip变量存储浮点型小费金额,导致计算结果被整数截断,最终输出错误。
错误原因拆解
用示例输入计算:
- 账单金额:12.50
- 税率8.875% → 税金额 = 12.50 × 0.08875 = 1.109375
- 加税后总金额:12.50 + 1.109375 = 13.609375
- 20%小费应为:13.609375 × 0.2 = 2.721875
但你的代码中,tip是int类型,把2.721875赋值给它时会直接截断小数部分,变成整数2。这导致总金额少了0.721875,平分后自然得到错误的7.80。
修复后的代码
不要复用int类型的tip参数,新建浮点型变量存储计算结果,或者直接简化计算逻辑:
#include <cs50.h> #include <stdio.h> float half(float bill, float tax, int 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: "); printf("You will owe $%.2f each!\n", half(bill_amount, tax_percent, tip_percent)); } float half(float bill, float tax, int tip) { // 先计算加税后的总金额 float total_after_tax = bill * (1 + tax * 0.01); // 再计算加小费后的总金额,最后平分 return total_after_tax * (1 + tip * 0.01) / 2; }
验证结果
用示例输入运行:
- 加税后总金额:12.5 × 1.08875 = 13.609375
- 加小费后总金额:13.609375 × 1.2 = 16.33125
- 平分后:16.33125 / 2 = 8.165625,
printf输出%.2f会四舍五入为8.17,符合正确结果。
内容的提问来源于stack exchange,提问作者blueetfm
相关产品推荐
相关产品推荐

