Gurikar said:
Hello,
Can any one tell me is the code below correct.
#include<iostream.h>
/* get modern!Use #include said:
/*
** you would be better served using int main(void), if you are
** not going to use the arguments passed to main)
*/
{
int i = 1;
float f = i / 2;
Here what goes on under the hood is: i i.e. integer 1 is
divided by integer 2, which is zero, in integer arithmetic,
and the result is then stored to a float f.
Here value of float is zero, so the if condition fails, and
you get the else branch executed.
However, you are really lucky, as relational operators on floats
are not likely to give you correct result, when you do not take
into account a small tolerance.This is because of the way
floating point numbers(which are rarely exactly representable
using a finite number of bits) are internally stored as a bit pattern.
cout<<"HI";
else
cout<<"Hello";
/* int main(), expects you to give back an int */
return 0;
}
Does the above correct.
Depends on what you mean by *correct*.
Initially i felt output should be
unpredictable..Am i right..But when i tried in my compiler(VC7),,its
printing Hello..Is this right...Why????
If you want to print "Hello", use something like:
float f = (float)i / 2; /* or */
float f = i / 2.0f; /* or */
float f = (float)i / 2.0f; /* or */
and change the if (cond...) to
if ( fabs(f) < EPSILON ) /* we are sufficiently close to
zero(?)*/
where EPSILON maybe
const float EPSILON = 0.0000001f;
HTH,
Suman.