在比较三个浮点数时双重不等式

cha*_*esh 1 c++ floating-point

有人可以告诉我为什么以下不起作用?(我的意思是没有输出)

if(0.0001<0.001<0.01)   
    cout<<"hi\n"<<endl;
output:    (blank)
Run Code Online (Sandbox Code Playgroud)

虽然以下工作:

if(0.0001<0.001 && 0.001<0.01)  
    cout<<"hi\n"<<endl;
  output:hi
Run Code Online (Sandbox Code Playgroud)

Jac*_*ack 6

因为<C++中没有神奇的n-ary 运算符.

0.0001 < 0.001 < 0.01 
Run Code Online (Sandbox Code Playgroud)

被解析(因为<是左关联的)

(0.0001 < 0.001) < 0.01
Run Code Online (Sandbox Code Playgroud)

0.0001 < 0.001返回值为value的booltrue.现在你有了

true < 0.01
Run Code Online (Sandbox Code Playgroud)

但是根据标准,true当转换为整数类型时,布尔值为1,所以你有

1 < 0.01
Run Code Online (Sandbox Code Playgroud)

这是假的.