Chaining of Relational operators is giving wrong output [closed]

天涯浪子 提交于 2019-12-02 13:41:25

In your code, what you've tried

 else if(18.5<=bmi<23)

No, this kind of chaining of Relational operators is not possible in C. You should write

 else if((18.5<=bmi) &&  (bmi < 23))

to check bmi value in [18.5, 23) and so on for the other cases.


EDIT:

Just to elaborate about the issue, an expression like

18.5<=bmi<23

is perfectly valid C syntax. However, it is essentially the same as

((18.5<=bmi) < 23 )

due to the operator associativity.

So, first the (18.5<=bmi) is evaluated and the result , (0 or 1) gets to get comapred against 23, which is certainly not you want here.

This:

18.5<=bmi<23

means the same as

(18.5 <= bmi) < 23

In other words the value of bmi is never compared to 23. You must not use that kind of math-syntax in C, it should be written as:

(18.5 <= bmi) && (bmi < 23)

So it's really two comparisons of the variable, and must be written using the boolean-and (&&) operator to make this explicit.

Yes, C language does show you the right answer of what you've tried.

There is no syntax like this in C for comparison (but yes, it's a valid syntax):

else if(18.5<=bmi<23)

it should be this:

else if((18.5<=bmi)&&(bmi < 23))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!