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

在C语言中如何仅打印浮点数小数点后的整数部分

解决方案

要实现将浮点数金额拆分为整数美元和整数美分输出,需注意规避浮点数精度误差问题,正确实现方式如下:

#include <stdio.h>
// 如需使用round函数需引入math.h,编译时要加-lm参数
#include <math.h>

int main() {
    double cost = 12.88;
    // 先转换为总美分数,做四舍五入避免精度误差
    int total_cents = (int)round(cost * 100);
    int dollars = total_cents / 100;
    int cents = total_cents % 100;
    printf("%d dollars and %d cents", dollars, cents);
    return 0;
}

如果不想引入math库,也可以用加0.5后强转的简易四舍五入方案:

#include <stdio.h>

int main() {
    double cost = 12.88;
    int total_cents = (int)(cost * 100 + 0.5);
    int dollars = total_cents / 100;
    int cents = total_cents % 100;
    printf("%d dollars and %d cents", dollars, cents);
    return 0;
}

两种方案运行后都会输出你需要的效果:

12 dollars and 88 cents

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:21:00