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

C语言用int和double计算2加元硬币数量及余数编译报错求助

C语言零钱兑换程序报错原因及修复方案

报错产生原因

  • 报错1「表达式必须为整数类型」、报错4「'%'运算符非法:左操作数类型为'double'」:C语言中%取模运算符仅支持整数类型的操作数,你的代码中amount是double浮点数类型,不能直接参与取模运算,因此触发这两个报错。
  • 报错2「返回值被忽略:'scanf'」:scanf函数的返回值代表成功读取的输入项个数,Visual Studio的安全编译规则默认要求开发者处理该返回值,用于判断用户输入是否合法,你代码中未接收处理该返回值因此触发告警。
  • 报错3「'='赋值操作从'double'转换到'int',可能存在数据丢失」:toonie是int整数类型,amount / 2的运算结果是double浮点数类型,直接赋值时编译器会做隐式类型转换,小数部分会被截断丢弃,因此编译器提示存在数据丢失风险。

另外你的代码还存在隐含问题:一是用double存储金额容易出现浮点数精度误差,比如0.1无法被二进制浮点数精确表示,最终计算结果可能偏差;二是toonie是int类型,输出时用了%ld格式符,类型不匹配会导致输出异常。

修复方案

建议优先将金额转换为以分为单位的整数进行运算,彻底规避浮点数精度问题,同时解决上述所有编译报错,修复后代码如下:

#include <stdio.h>
#include <math.h>

int main()
{
    double amount;
    int total_cents;
    int toonie_count;
    int remainder_cents;
    double remainder_amount;

    printf("Change Maker Machine\n");
    printf("====================\n");
    printf("Enter dollars and cents amount to convert to coins: $");
    // 接收scanf返回值,判断输入是否合法
    int read_ret = scanf("%lf", &amount);
    if (read_ret != 1 || amount < 0) {
        printf("输入金额不合法\n");
        return 1;
    }

    // 转换为以分为单位的整数,四舍五入避免浮点数精度误差
    total_cents = (int)round(amount * 100);
    // 整数运算计算2加元硬币数量,2加元=200分
    toonie_count = total_cents / 200;
    // 整数取模计算剩余金额
    remainder_cents = total_cents % 200;
    // 转换回元为单位
    remainder_amount = remainder_cents / 100.0;

    printf("%d is the amount of toonies you need\n", toonie_count);
    printf("%.2lf is the remainder for your change\n", remainder_amount);

    return 0;
}

如果你坚持要用浮点数运算,可以用fmod函数替代%取模运算符,同时显式转换类型、处理scanf返回值即可,但依然存在浮点数精度风险。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 16:54:03