+ 2
Why does this program print "Solo" and not "Learn"
float a=0.7; if(a<0.7) cout<<"Solo"<<endl; else cout<<"Learn"<<endl;
29 Answers
+ 7
Floating point precision is not accurate, never compare equality directly with them.
0.7 as a floating point could be 0.6999999..
Hence, is less than 0.7.
If you want to compare floating points try to remove the possible error gap.
Something like:
if (a < 0.7 - 0.000001)
Should do.
+ 5
I agree with @James if the case was
if (a <= 0.7){
cout << " Solo"
// would print
}
+ 5
@Shashank
that is true!
so if I say
0.2 > 0.7
it is false
The compiler checks
and when true or false is known this happens
if( 0.2 < 0.7){
// true
} else {
//false
}
+ 5
@Shashank
when you said
0.7
was greater
You knew there was only one answer
The compiler is the same
if "if" is CORRECT ONLY it code inside the if is executed
if "if" is WRONG ONLY the code in else is executed
+ 4
I can provide an example.
It will be completed shortly.
+ 4
Another example
- enter a float
ex: 0.4
https://code.sololearn.com/cWKuIrmztc6s/?ref=app
+ 3
That is because only one case is seleted in the if/else case not both.
+ 3
Here is an example
https://code.sololearn.com/cT6I5FfHq1Ck/?ref=app
+ 3
@Shashank
Which is greater?
0.2 or 0.7
+ 3
It is because of precision error. Like when you store 0.7 as float, it will be stored in binary form in the memory with extra padding of bits e.g. 0.69999999
and when you compare it with exact 0.7, the result is true bcoz 0.69999999 is less than 0.7 Hence, "Solo" is printed.
If you compare it with 0.7f "Learn" will print bcoz this 0.7f too will be stored as 0.69999999
+ 3
you took int a = 0.7;
a will be 0 because int never takes floating point.
hence 0 < 0.7 will be true
if you give int a = 1.7;
a will be 1
if .... int a = 5.0;
a will be 5
+ 3
Floating point values are not precise.
+ 3
@Ray this article would help http://www.geeksforgeeks.org/floating-point-representation-basics/
+ 2
@manual: 0.7 obviously!
+ 2
If the if statement is true, the else is not printed.
+ 2
kartikey: i tried on all data types!
Why isn't the else part getting executed!
Why and how is a decimal value treated to be less than itself?
+ 1
@Manual: Sry I didn't get you!
Would you mind being more specific and explain with a reason for your solution!
Thank you
+ 1
from Your Code You didnt specify What it will print when you input value of a =0.7 You only inputed if (a <0.7)
you will see if you put lower value like 0.6 it will print 'learn'
why dont you give it a less than nd Equal to Value
+ 1
Ok then try the same program by replacing ""a=0.7"" by ""a=0.2"" and ""if(a<0.7)"" by ""if(a<0.2)
then you'll get learn as output.
how's that possible
+ 1
@Restoring_faith: I appreciate your answer!
but that problem of not printing the else part prevails even after changing the data type to int