为什么 printf 舍入浮点数? [英] Why printf round floating point numbers?
问题描述
我正在尝试使用 printf
打印一些浮点数.例如:
I am trying to print some floating point numbers using printf
.
For example:
int main()
{
printf("%.1f",76.75);
return 0;
}
输出:76.8
我对结果有一些疑问.
首先,为什么不打印 76.7?
First of all, why didn't it print 76.7?
第二,如何四舍五入?
推荐答案
C99 §7.19.6.1
fprintf
函数
f
,F
表示浮点数的 double
参数以 [−]ddd.ddd
样式转换为十进制表示法,其中小数点后的位数-点字符等于精度规范.如果精度缺失,则取6;如果精度为零且未指定 #
标志,则不会出现小数点字符.如果出现小数点字符,则在其前面至少出现一位数字.该值四舍五入到适当的位数.
A double
argument representing a floating-point number is converted to decimal notation in the style [−]ddd.ddd
, where the number of digits after the decimal-point character is equal to the precision specification. If the precision is missing, it is taken as 6; if the precision is zero and the #
flag is not specified, no decimal-point character appears. If a decimal-point character appears, at least one digit appears before it. The value is rounded to the appropriate number of digits.
这篇关于为什么 printf 舍入浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!