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

CS50作业Half代码异常:小数输入结果错误,整数输入正常求助

CS50 Half作业小数输入计算错误原因分析与修复

问题场景

在完成CS50的Half作业时,输入整数参数(如账单100、税率20%、小费10%)计算结果正确,但输入以下小数参数时:

Bill before tax and tip: 12.50
Sale Tax Percent: 8.875
Tip percent: 20
实际输出为$7.80,而非预期的$8.17。

原代码如下:

#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 price;
    tax = bill * tax / 100.0;
    tip = (bill + tax) * tip / 100;
    price = bill + tax + tip;
    return price / 2;
}

错误原因

核心问题是函数参数类型不匹配与变量复用导致的精度丢失:

  • 函数参数tip是int类型,但计算小费时,(bill + tax) * tip / 100的结果是浮点数值,直接赋值给int类型的tip变量会自动截断小数部分,造成精度损失。
  • 以测试用例为例:
    1. 计算税额:12.5 * 8.875 / 100 = 1.109375(正确存储在float类型的tax变量中)
    2. 计算小费:(12.5 + 1.109375) * 20 / 100 = 2.721875,但赋值给int类型的tip时,小数部分被截断,tip变成2
    3. 总金额:12.5 + 1.109375 + 2 = 15.609375,除以2后得到7.8046875,最终输出$7.80
  • 整数输入时,计算出的小费恰好是整数,截断后无精度损失,因此结果正确。

修复方案

不要复用函数的参数变量,重新定义浮点类型的局部变量存储计算后的税额和小费,避免类型截断:

修复后的代码:

#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_percent, int tip_percent)
{
    float tax_amount = bill * tax_percent / 100.0;
    float tip_amount = (bill + tax_amount) * tip_percent / 100.0;
    float total_price = bill + tax_amount + tip_amount;
    return total_price / 2;
}

验证结果

用测试用例计算:

  1. 税额:12.5 * 8.875 / 100 = 1.109375
  2. 小费:(12.5 + 1.109375) * 20 / 100 = 2.721875
  3. 总金额:12.5 + 1.109375 + 2.721875 = 16.33125
  4. 平分后:16.33125 / 2 = 8.165625,最终输出$8.17,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:35:15