在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
相关产品推荐
相关产品推荐

