0

我有一个舍入功能,

float myround(float x, int places)
{
   float const shift = powf(10.0f, places);
   x *= shift;
   x = floorf(x + 0.5f);
   x /= shift;

   return x;
}

当我尝试将数字四舍五入到小数点后 4 位,然后用

printf("%f ", x); 

我得到了没有四舍五入的数字。如果我打印它

printf("%.4f ", x);

我把数字四舍五入到 4 位。第一个 printf 是否应该不将数字打印到小数点后 4 位,因为我已经将数字四舍五入了?

谢谢。

4

2 回答 2

2

您不能对浮点数进行舍入,只能将它们打印到特定的精度。所有浮点数始终是“未舍入的”,尽管您显然可以将值更改为更接近舍入的数量。

于 2013-05-20T22:00:29.267 回答
0

man printf

f, F   The double argument is rounded and 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 explicitly zero, no decimal-point character appears. If a decimal point  appears,  at  least one
       digit appears before it.

The fprintf(), printf(), sprintf(), vprintf(), vfprintf(), and vsprintf() functions conform to C89 and C99.

所以,不,如果你不提供它,它不应该做任何事情,除了以 6 作为精度。

于 2013-05-20T22:09:39.840 回答