CS50 Week 1 'Half'练习程序输出异常,请求排查问题
CS50 Half练习题计算错误排查
我正在完成CS50的「Half」练习题,但程序无法输出正确的十进制数值。以下是我的当前代码:
// Calculate your half of a restaurant bill // Data types, operations, type casting, return value #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)); } // TODO: Complete the function float half(float bill, float tax, int tip) { float tax_amt = bill * (tax / 100.0); float tip_amt = bill * ((float)tip / 100.0); float total = bill + tax_amt + tip_amt; return total / 2; }
预期输出:
Bill before tax and tip: 12.50 Sale Tax Percent: 8.875 Tip percent: 20 You will owe $8.17 each!
实际输出:
Bill before tax and tip: 12.50 Sale Tax Percent: 8.875 Tip percent: 20 You will owe $8.05 each!
请问问题出在哪里?
问题原因
你的代码里,小费是基于原始未税账单计算的,但实际餐厅账单的小费通常是基于含税后的总账单计算的,这就是数值偏差的核心原因。
修正后的代码
// Calculate your half of a restaurant bill // Data types, operations, type casting, return value #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)); } // TODO: Complete the function float half(float bill, float tax, int tip) { float tax_amt = bill * (tax / 100.0); float bill_with_tax = bill + tax_amt; // 先计算含税账单总额 float tip_amt = bill_with_tax * ((float)tip / 100.0); // 基于含税账单计算小费 float total = bill_with_tax + tip_amt; return total / 2; }
验证计算过程
用测试数据一步步核对:
- 原始账单:12.50
- 税额:12.50 × 8.875% = 1.109375
- 含税账单:12.50 + 1.109375 = 13.609375
- 小费:13.609375 × 20% = 2.721875
- 总账单:13.609375 + 2.721875 = 16.33125
- 每人应付:16.33125 ÷ 2 = 8.165625,保留两位小数后即为8.17,与预期输出一致。
内容的提问来源于stack exchange,提问作者brinkbrink
相关产品推荐
相关产品推荐

