Mail Archives: djgpp/1997/10/16/00:32:20
Oon Lin <Oon DOT Lin AT jcu DOT edu DOT au> wrote:
> Hi !
> I was doing a simple printf but it seems like I don't get the result I
> want...
> The statement was :
> printf("Vertical Retrace Time = %f \n", 1/70) ;
> I was careful to use '\n' to force the statement above to be printed out
> but what I got was
> Vertical Retrace Time = 0.000000
> Wha ???
> When I cast the calculation
>
> printf("Vertical Retrace Time = %f \n", (float)(1/70)) ;
> I got the result that I want....
> Is this a bug in GNU ??
No. 1 and 70 are both 'int's. The result of the division of two 'int's is
an 'int', NOT a float. Since the result of 1/70 is a decimal, it is truncated;
in this case to 0. Casting the experssion to a 'float' forced gcc to divide
them as floats. To avoid the cast, you can write:
printf("[...] %f [...]\n", 1.0/70.0);
The decimal places instruct gcc that these numbers are 'float's ('double's
actually, IIRC) and thus the result of the division is also 'float'.
--
[- firewind -]
[- email: firewind AT metroid DOT dyn DOT ml DOT org (home), firewind AT aurdev DOT com (work) -]
[- "You're just jealous because the voices talk to -me-." -]
[- Have a good day, and enjoy your C. -]
[- (on a crusade of grumpiness where grumpiness is due) -]
- Raw text -