printf,如何为整数插入小数点
我有一个UINT16
无符号整数
4455, 312, 560 or 70.
如何使用printf在最后两位数之前插入小数点,以便示例数字显示为
44.55, 3.12, 5.60 or 0.70
如果没有printf解决方案,还有其他解决方案吗?
我不想使用浮点数。
%.2d
可以添加额外的填充零
printf("%d.%.2d", n / 100, n % 100);
例如,如果n
为560
,则输出为: 5.60
编辑 :根据@Eric Postpischil的评论,我最初没有注意到它是UINT16
,最好使用:
printf("%d.%.2d", (int) (x/100), (int) (x%100));
printf("%d.%.2d", x / 100, x % 100);
您可以直接使用printf而不 使用float
printf("%d.%02d", num/100, num%100);
%02d表示右对齐零填充。
if num is 4455 ==>output is 44.55 if num is 203 ==>output is 2.03
编辑:
通过查看来自@ Eric Postpischil的评论,最好像这样使用。
printf("%d.%02d", (int) (num/100), (int) (num%100));