On Sunday 09 January 2011 04:24:40 priya mehta wrote:
> #include<stdio.h>
> int main()
> {
> float a=275.7;
> if(275.7>a)
> printf("Hi");
> else
> printf("Hello");
> return 0;
> }
>
> #include<stdio.h>
> int main()
> {
> float a=75.7;
> if(75.7>a)
> printf("Hi");
> else
> printf("Hello");
> return 0;
> }
>
> why the above two programs give different output?
If you add a printf("%f\n", a) after each variable initialization, you'll get:
- for 275.7 -> 275.700012
- for 75.7 -> 75.699997
The C compiler treats real constants as 'double'-s which is why you get
'Hello' for first and 'Hi' for the second. If the 'if' from the second program
becomes:
if ((float)75.7 > a) [...]
then you'll get a 'Hello'. Floating point, single precision, is not always a
good choice: http://en.wikipedia.org/wiki/Single_precision
You might want to use 'double' to keep future surprises out of the way.
--
Mihai Donțu
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.