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

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;
}

验证计算过程

用测试数据一步步核对:

  1. 原始账单:12.50
  2. 税额:12.50 × 8.875% = 1.109375
  3. 含税账单:12.50 + 1.109375 = 13.609375
  4. 小费:13.609375 × 20% = 2.721875
  5. 总账单:13.609375 + 2.721875 = 16.33125
  6. 每人应付:16.33125 ÷ 2 = 8.165625,保留两位小数后即为8.17,与预期输出一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:45:01