如何将两个if语句合并为一个
How to combine two if statements into one
嗨,我有这两个单独的if
语句,当这样放的时候;
if (powerlevel <= 0) // <--- ends up having no effect
if (src.health <= 0)
the_thing_to_do();
如何将这两个if语句合并为一个?有可能吗?如果是,怎么办?
如果希望两个语句都为true,请使用逻辑AND
if(powerlevel <= 0 && src.health <= 0)
如果您希望任一语句为真,请使用逻辑OR
if(powerlevel <= 0 || src.health <= 0)
以上两个运算符都是逻辑运算符
如果希望同时满足(逻辑AND),请使用operator&&
if(powerlevel <= 0 && src.health <= 0) { .. }
或者operator||
,如果你只想满足一个(逻辑or)
if(powerlevel <= 0 || src.health <= 0) { .. }
这取决于您是否希望两者都求值为true。。。
if ((powerlevel <= 0) && (src.health <= 0)) {
// do stuff
}
或者至少一个。。。
if ((powerlevel <= 0) || (src.health <= 0)) {
// do stuff
}
区别是逻辑AND(&&)或逻辑or(||)
如果它是有意义的(有时),那么它只是一个aternative。
Both true:
if (!(src.health > 0 || powerlevel > 0)) {}
at least one is true:
if (!(src.health > 0 && powerlevel > 0)) {}
或者如果您不想使用&;你可以使用三元算子
#include <iostream>
int main (int argc, char* argv[])
{
struct
{
int health;
} src;
int powerlevel = 1;
src.health = 1;
bool result((powerlevel <= 0) ? ((src.health <=0) ? true : false) : false);
std::cout << "Result: " << result << std::endl;
}
相关文章:
- 如何将一个数组值合并为一个整数c++
- 如何将不同的可执行文件合并到一个窗口框架中进行编码?像浏览器一样
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 将两个 cpp 文件合并为一个 cpp 文件
- 将所有 *.txt 文件合并到一个文本文件中,其名称由用户使用 C++ 提供
- C++ 如何将两个 makefile 对象目标规则(位于另一个文件夹中)合并到一个目标/规则中?
- 将两个列表合并为一个蛇形列表
- 使用迭代器进行合并排序中的一个缓冲区
- 如何通过通用引用或std::forward将这三个c++模板函数合并为一个
- C将链接库合并为一个库
- 是否可以将前向声明和常规声明合并到一个文件中,然后像分开一样使用它?
- 我正在编写一个拆分为 3 的合并排序,我不知道为什么它不起作用
- 两个 cin / cout 语句合并为一个
- 我想将四个字节合并为一个数字以进行串行传输
- 将两个 1D 直方图合并为一个
- 如何合并两个双重链接列表(访问下一个链接)
- 将 3 个列表合并到一个大列表中
- C++全局常量数组:是否保证合并(优化)到一个副本中
- 如何合并一个pImpl接口,同时也允许WndProc与之交互
- 合并一个类的两个数组