Question : void main() { float a= 0.7; if (a < 0.7) printf("c"); else printf("c++"); } Output of the above program is c. Why? Whereas the same program with 0.8 instead of 0.7 gives c++ as the output? Why explain?
this is because of rounding the value of variable a. i.e. a=0.7 is rounded to =0.699999988 and the constant 0.7 is as =0.69999999999 so a<0.7 ii true so it print "c" but in case of 0.8 a=0.800000011 and constant 0.8 is 0.8000000000000000
In c any real number is treated as double. So, when you compare 'a' with 0.7, complier is comparing float number with a double which results into printing - C. To tell the compiler that you want to compare 'a' with float 0.7 you can change the program as follows: #include<stdio.h> void main() { float a = 0.7; if(a <0.7f) printf("C"); else printf("C++"); }
All floating values like 0.1 or 0.7 r treated as double values internally.here a is float value and 0.7 is double value therefore double has more precisions than float.In comparison operation it checks each precision values. as all precision values are not equals it will go in else part and print c++.
floating point number can't be compared directly. So in order to compare the numbers we need to find the absolute value of the floating point (i.e precision) and then compare the number.
By default, the compiler takes value of 0.7 in the line " if (a < 0.7)" as double and that of a is float. Hence the difference. But for 0.8, the value of double and float are the same.
In C, floating point constant is stored as a long double,because of precision considerations.That's why,in 'a',instead of 0.7,0.666698 gets stored.Hence the answer....while comparing,do: while(a<(float)0.7)
Whenever we use the floating point number then that floating point number is stored in to memory into the 32 bit (IEEE)(754) format that means in (sign, exponent, mantissa ). if you will convert the 0.7 then the mantissa value will be .69999.so that it will print output "C".
we have problems with decimal to binary conversions for .7. it cannot b expressed correctly in finite binary. it is always rounded of to .69999999 for that . howver .8 is exact in binary too
There is a limitation of floating no in c.Variable cant store exact value of float.It stores some of less value. In this case it store the less than .7 value.so if condition becomes true and answer will be c.