请告诉我以下代码的答案是1 [英] plz explain me that how the answer of following code is 1

查看:62
本文介绍了请告诉我以下代码的答案是1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码是:



code is:

int a=20,b=10,c=5;
int I= a<b<c;
cout<<I;

推荐答案

我会说编译并亲自看看...... ,但是使用C ++,它甚至都不会编译。您需要将 i 声明为布尔值( bool )。或者说,甚至 int ,因为布尔实际上是实现为整数。







我抓住了关于不编译代码的话,因为OP后来在问题的文本中修复了它。 OP可以编译它,看看发生了什么。



[结束编辑]



这是提示为你: bool i = a< b< c; 将被编译,因为它是 bool i =(a< b)< c; a< b 是布尔值。



现在,编译并运行它,看看发生了什么并尝试解释它。这很容易。



对结果感到惊讶?然后尝试使用调试器逐步查看正在进行的操作。比较:

I would say "compile it and see by yourself"…, but with C++, it won't even compile. You need to declare i as Boolean (bool). Or, say, even int, because Boolean is actually implemented as integer.



I scratched the words about not compiling code because OP later fixed it in the text of the question. OP could compile it and see what's going on.

[END EDIT]

Here is the hint for you: bool i = a < b < c; will be compiled as it was bool i = (a < b) < c; and a < b is Boolean.

And now, compile and run it, see what's going on and try to explain it. It's going to be easy enough.

Surprised with the result? Then try to see what's going on step by step, using the debugger. Compare with:
bool i = (a < b) & (b < c);





请注意,开发人员的真实意图可能是上面显示的行,很有可能,所以你问题中的表达将是误解的结果。现在想想你为什么总要避免像你的问题所示的表达式,将比较结果与数字操作数混合。这应该是从这个荒谬的例子中学到的真正教训,从这个意义上说,它应该对你有用。



-SA


好吧,20不小于10,所以 a< b 结果为0; 0小于5,因此(a< b)< c 的结果为1.您期望什么?
Well, 20 is not less than 10, so a<b results in 0; 0 is less than 5, so the result of (a<b)<c is 1. What did you expect?


这篇关于请告诉我以下代码的答案是1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆