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

C语言现金找零计算程序无法正确输出分币数量问题求解

问题根因

你遇到的问题确实是owing变量用int类型存储美元为单位的金额,直接截断了小数部分的美分数。以你给出的测试用例为例,实付减应付得到124.15美元,转int后直接变为124,15美分被丢弃,自然无法正确计算分币找零。
另外直接用浮点数处理金额还存在精度误差问题,比如0.1无法被二进制浮点数精确存储,计算过程中可能出现1美分的偏差,更稳妥的做法是将所有金额转换为以美分为单位的整数进行计算,全程用整数运算避免误差。

修正后的代码
#include <stdio.h>

int main(){
    double owed, paid;

    printf("Enter amount owed: ");
    scanf("%lf", &owed);

    printf("Enter amount paid: ");
    scanf("%lf", &paid);

    // 转换为美分整数,加0.5实现四舍五入避免浮点误差
    int owing_cents = (int)((paid - owed) * 100 + 0.5);
    int count;

    // 50美元=5000美分
    count = owing_cents / 5000;
    if (count > 0) printf("%d fifty dollar bill\n", count);
    owing_cents = owing_cents % 5000;

    // 20美元=2000美分
    count = owing_cents / 2000;
    if (count > 0) printf("%d twenty dollar bill\n", count);
    owing_cents = owing_cents % 2000;

    // 10美元=1000美分
    count = owing_cents / 1000;
    if (count > 0) printf("%d ten dollar bill\n", count);
    owing_cents = owing_cents % 1000;

    // 5美元=500美分
    count = owing_cents / 500;
    if (count > 0) printf("%d five dollar bill\n", count);
    owing_cents = owing_cents % 500;

    // 2美元硬币=200美分
    count = owing_cents / 200;
    if (count > 0) printf("%d two dollar coin\n", count);
    owing_cents = owing_cents % 200;

    // 25美分硬币
    count = owing_cents / 25;
    if (count > 0) printf("%d quarter\n", count);
    owing_cents = owing_cents % 25;

    // 10美分硬币
    count = owing_cents / 10;
    if (count > 0) printf("%d dime\n", count);
    owing_cents = owing_cents % 10;

    // 5美分硬币
    count = owing_cents / 5;
    if (count > 0) printf("%d nickel\n", count);
    owing_cents = owing_cents % 5;

    return 0;
}
运行效果

用你给出的测试用例运行,输出结果和预期完全一致:

Enter amount owed: 16.50
Enter amount paid: 140.65
2 fifty dollar bill
1 twenty dollar bill
2 two dollar coin
1 dime
1 nickel

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:15:02