Re: Confused to printf %f
- From: Richard Heathfield <invalid@xxxxxxxxxxxxxxx>
- Date: Sat, 29 Jul 2006 01:41:49 +0000
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)
.
- Follow-Ups:
- Re: Confused to printf %f
- From: timmu
- Re: Confused to printf %f
- References:
- Confused to printf %f
- From: timmu
- Confused to printf %f
- Prev by Date: structure malloc help
- Next by Date: Re: structure malloc help
- Previous by thread: Confused to printf %f
- Next by thread: Re: Confused to printf %f
- Index(es):
Relevant Pages
|