Re: Confused to printf %f



timmu said:


Someone asked me a question about integer division and printf
yesterday,
I tell him he should do a casting to float/double before you do any
interger division.

Why?

But he doesn't think so, so I try to do some example to explain,
However, after some trying,
I confused when I try to do some integer constant division,

If you are confused yourself, why did you "tell him" what he should do?

I know I should do float division something like 3.0/6.0,

That isn't a float division.

but I'm still confused where the -0.124709 comes for the following
example?

You lied to the compiler, and it got its revenge.

<snip>

//example 1
#include <stdio.h>
int main()
{
//double i;
//long a=1,b=4;
printf("%f\n",3/7);

3 is an int, 7 is an int, and so it's not surprising that 3/7 is an int. But
by using %f, you said to printf: "I'm giving you a double". But you didn't
give it a double. You gave it an int. If you lie to the compiler, it will
wreak its revenge.

Use %d to print ints.

<snip>

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
.



Relevant Pages

  • Re: c interview
    ... undefined behaviour because printf is a varidac function. ... stdio.h before using printf and other headers as appropriate before ... Would make it a point that the size of int is assumption to be .... ...
    (comp.lang.c)
  • Re: How to get total heap size of a process
    ... snip ... ... int main ... Because printf can't handle a size_t? ... They never stop thinking about new ways to harm our country ...
    (comp.lang.c)
  • Re: Confused to printf %f
    ... Someone asked me a question about integer division and printf ... is an int, 7 is an int, and so it's not surprising that 3/7 is an int. ... Richard Heathfield ...
    (comp.lang.c)
  • Re: First program in C - what is going on with function returns?
    ... The program is compiling ok but I receive this warning: ... char *speakdate(int d, int m, int y) ... printf ("Your date of birth is ...
    (comp.lang.c)
  • Re: Printf
    ... "pete" wrote in message ... >> If you have an integer, how to print it out without using printf? ... > int fsput_u ...
    (comp.lang.c)