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

CS50 HALF练习题代码调试求助:功能正常但输出不符预期

问题排查与修复:CS50 Half练习题逻辑错误

你的代码核心问题是小费计算的基数错误,完全不符合题目要求的计算流程:

题目明确要求的计算顺序是:

  1. 原始账单金额 + 税费 → 得到含税账单
  2. 以含税账单为基数计算小费 → 得到含税加小费的总金额
  3. 总金额 ÷ 2 → 每人应付的金额

但你的代码中,小费是基于原始账单金额计算的,而非含税后的金额,这直接导致所有测试用例的结果偏小。

修正后的代码

// 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 bill_with_tax = bill + bill * (tax / 100.0);
    // 第二步:基于含税账单计算小费,得到总金额
    float total_amount = bill_with_tax + bill_with_tax * (tip / 100.0);
    // 第三步:平分总金额
    float half_amount = total_amount / 2;
    // 手动四舍五入到两位小数(也可依赖printf的%.2f自动处理)
    return ((int)(half_amount * 100.0 + 0.5) / 100.0);
}

测试用例验证

测试用例1:账单12.50、税率8.875%、小费20%

  1. 含税账单:12.50 + 12.50*(8.875/100) = 13.609375
  2. 总金额(含税+小费):13.609375 + 13.609375*(20/100) = 16.33125
  3. 平分后:16.33125 / 2 = 8.165625,四舍五入后为8.17,符合预期。

测试用例2:账单50、税率10%、小费20%

  1. 含税账单:50 + 50*(10/100) = 55
  2. 总金额:55 + 55*(20/100) = 66
  3. 平分后:66 / 2 = 33.00,完全符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 05:50:44