开发者

Integer to floating conversion in C

float f1 开发者_开发技巧= 123.125;
int i1 = -150;

f1 = i1;    // integer to floating conversion
printf("%i assigned to an float produces %f\n", i1, f1);

Output:

-150 assigned to an float produces -150.000000

My question is why the result has 6 zeros (000000) after the . and not 7 or 8 or some number?


That's just what printf does. See the man page where it says

f, F

The double argument shall be converted to decimal notation in the style "[-]ddd.ddd", where the number of digits after the radix character is equal to the precision specification. If the precision is missing, it shall be taken as 6; if the precision is explicitly zero and no '#' flag is present, no radix character shall appear. If a radix character appears, at least one digit appears before it. The low-order digit shall be rounded in an implementation-defined manner.

(emphasis mine)

It has nothing to do with how 150 is represented as a floating point number in memory (and in fact, it's promoted to a double because printf is varargs).


The number of zeros you see is a result of the default precision used by the %f printf conversion. It's basically unrelated to the integer to floating point conversion.


Because the C standard (§7.19.6.1) says that in the absence of information to the contrary, %f will print 6 decimal places.

f,F 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.


Floating point arithmetic is not exact. printf is just showing that number of zeroes.

From the documentation:

The default number of digits after the decimal point is six, but this can be changed with a precision field. If a decimal point appears, at least one digit appears before it. The "double" value is rounded to the correct number of decimal places.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜