Answered by:
why the compiler behaves like this

Question
-
hi friends,
just guess the output of the following piece of code
main ( )
{
printf("%f",5/2);
}
do u find the output not what u expected.. can u explain me why?Wednesday, February 28, 2007 12:10 PM
Answers
-
it's an integer division, and it should give the answer as 2.
the rules are :
integer / integer = integer
integer / float = float
float / integer = integer
(float)integer / integer = float
Wednesday, February 28, 2007 6:28 PM -
ok but... when the compiler gives an output for the folowing code
main()
{
printf("%d",4/2);
}
why does it produce error in the earlier case?Thursday, March 1, 2007 12:07 PM -
it's simple. in this case, its a direct integer division, and is following the arithmetic rules of C, as mentioned in previous post of mine.
mark my post as answer, if you've got answers for your question.
Thursday, March 1, 2007 7:56 PM -
dude make that statement as
printf("%f",(float)5/2);
it will work..bcoz ince the result is integer it is tryin to cast that integer into float thus showing the garbage value..
Friday, March 2, 2007 10:16 AM -
well thanks buddy... watch out for more interesting things in this spaceTuesday, March 6, 2007 3:51 PM
-
hmm wel thanks for the replies friendsMonday, March 12, 2007 11:35 AM
-
sure m8.. i ll update soonTuesday, March 13, 2007 11:36 AM
All replies
-
it's an integer division, and it should give the answer as 2.
the rules are :
integer / integer = integer
integer / float = float
float / integer = integer
(float)integer / integer = float
Wednesday, February 28, 2007 6:28 PM -
ok but... when the compiler gives an output for the folowing code
main()
{
printf("%d",4/2);
}
why does it produce error in the earlier case?Thursday, March 1, 2007 12:07 PM -
it's simple. in this case, its a direct integer division, and is following the arithmetic rules of C, as mentioned in previous post of mine.
mark my post as answer, if you've got answers for your question.
Thursday, March 1, 2007 7:56 PM -
dude make that statement as
printf("%f",(float)5/2);
it will work..bcoz ince the result is integer it is tryin to cast that integer into float thus showing the garbage value..
Friday, March 2, 2007 10:16 AM -
ya santhosh is right...the problem is that the given constants have not been type casted properly...thats the reason for such drastic errors during runtime...Tuesday, March 6, 2007 3:44 PM
-
well thanks buddy... watch out for more interesting things in this spaceTuesday, March 6, 2007 3:51 PM
-
another solution is
main ( )
{
printf("%f",5.0/2.0);
}Saturday, March 10, 2007 8:54 AM -
hmm wel thanks for the replies friendsMonday, March 12, 2007 11:35 AM
-
i am waiting for another questions. please ask them here.Monday, March 12, 2007 5:47 PM
-
sure m8.. i ll update soonTuesday, March 13, 2007 11:36 AM