c++ - Unknown behaviour of OR operator in C++
问题描述
I have this code running by chance and when i put anything as the answer it is showing me correct. I know we have to put ans before YES and yay, but this code was compiled too, as i mentioned if i put any word as the input the output is correct:
string ans;
cin >> ans;
if(ans == "yes" || "YES" || "yay") {
cout << "Correct";
}else {
cout << "Incorrect";
}
解决方案
好的,这是逻辑运算符的优先级(L->R)和关联性:
(((ans == "yes") || "YES") || "yay")
由于 C/C++没有与 Python 不同的链接。
第一个:ans == "yes"
->str
比较str
第二:bool result of 1st || "YES"
-> bool
和str
比较=总是true
为"YES"
不为空
第三:true || "YES"
=总是true
因此,条件将始终为true
for"YES"
且不为"yay"
null。
推荐阅读
- vue.js - 如果字段包含数字,如何禁用按钮?Vue JS
- javascript - Material UI 中的自定义媒体查询
- python - 循环遍历 csv 文件中的单词并在 python 中替换
- css - 在 CSS / SCSS 中具有类的下一个兄弟姐妹
- javascript - 传单标记集群自动
- vim - 在vim中的一个命令中替换模式之前和之后的文本
- ffmpeg - ffmpeg 到 kurento rtp 流断断续续的视频问题
- javascript - 在 Javascript 中填充 JSON 中的动态值
- python - rpy2 在脚本结束时产生无用的警告
- mongodb - 使用 MongoDB Spring Data Aggregation 匹配日期时间字段的问题