+ 2

What will be the output of the code? Please explain the answer in simple words.

float a=0.7; if(a<0.7) { printf("yes"); } else { printf("no"); }

17th Sep 2017, 11:06 AM
Arpit Kharche
Arpit Kharche - avatar
5 Antworten
+ 3
On modern computers, numbers are represented in floating point numbers. There are 2 types of floats: one is simply called float and takes 24 bit for the mantissa (the part holding the number) and 8 bits for the exponent (the part holding the location of the decimal point). The other type is called double and uses a 53 bit mantissa and 11 bit exponent. It is more accurate than float, but takes 8 bytes, not 4. By default any numerical constant you use is a double. Thefore when you write 'float a=0.7' the 0.7 is converted into float format which is less accurate than the double format. The float mantissa is represented by the 24 bit integer M, where the float is M/(2^24) (forget the exponent I mentioned for the moment, it is not relevant in this example, and so is the sign bit which I did not even mention). When we try representing 0.7 as float, we will look for the closest M : If we do 0.7*(2^24) we get 11744051.2 so we round it down to M=11744051 and so a is stored internally as 11744051/(2^24)=0.699999988079071044921875 Since the default constants are double, which are closer to 0.7, then a will be less than 0.7 However, if you want to store 0.3 as float, you will get : 0.3*(2^24)=5033164.8 This means that this time we round it up to 5033165, and 0.3 in a floating point representation will be: 5033165/(2^24)=0.300000011920928955078125 Therefore it will be greater than 0.3
17th Sep 2017, 11:52 AM
Udi Finkelstein
Udi Finkelstein - avatar
+ 1
it`s going print `no` since the (a) is not biger than 0.7 its going to the else statement and print "no" if it was <= it would have printed "yes"
17th Sep 2017, 2:08 PM
jay
0
ty @Lakshay ...for making my idea , about the output more clear...
17th Sep 2017, 11:15 AM
Arpit Kharche
Arpit Kharche - avatar
0
@jay ,strangely the output is yes...try the code mentioned above by @lakshay
19th Sep 2017, 4:17 AM
Arpit Kharche
Arpit Kharche - avatar