Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double inequality while comparying three floating point numbers [duplicate]

Can somebody tell me why the following does not work?(I mean no output)

if(0.0001<0.001<0.01)   
    cout<<"hi\n"<<endl;
output:    (blank)

While the following works:

if(0.0001<0.001 && 0.001<0.01)  
    cout<<"hi\n"<<endl;
  output:hi
like image 391
CKM Avatar asked Oct 21 '25 04:10

CKM


2 Answers

Because there is no magical n-ary < operator in C++.

0.0001 < 0.001 < 0.01 

is parsed (since < is left-associative) as

(0.0001 < 0.001) < 0.01

and 0.0001 < 0.001 returns a value of type bool with value true. Now you have

true < 0.01

but according to the standard a true boolean has value 1 when converted to an integral type so you have

1 < 0.01

which is false.

like image 178
Jack Avatar answered Oct 22 '25 18:10

Jack


When you are using condition like

(0.0001<0.001<0.01)

It will check first 0.0001<0.001 i.e. true which returns 1 and now condition become

( 1< 0.01 )

which is false so returns 0 that's why printing nothing.

like image 20
Kamaldeep singh Bhatia Avatar answered Oct 22 '25 18:10

Kamaldeep singh Bhatia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!