2013-07-26 53 views
-1

您好我有这两个单独的IF语句,如果这样放置;如何将两个if语句合并为一个

if(powerlevel<=0) // <--- ends up having no effect 
if(src.health<=0) 
    the_thing_to_do(); 

如何将这两个if语句合并为一个?可能吗?如果是的话如何?

+5

任何学习资源都应该在if语句后很快处理。 – chris

+0

你是什么意思“最终没有效果”? – amdn

+0

只是出于好奇,第一个陈述会有什么影响?由于缺少{},它只会影响第二个if语句,对吗?不是the_thing_to_do? – PunDefeated

回答

4

使用operator&&如果你想他们都被满足(逻辑AND)

if(powerlevel <= 0 && src.health <= 0) { .. } 

operator||如果你想只是一个被满足(逻辑OR)

if(powerlevel <= 0 || src.health <= 0) { .. } 
5

如果你想这两个陈述是真实的使用逻辑与

if(powerlevel <= 0 && src.health <= 0) 

如果你想要该声明是真实的使用逻辑或

if(powerlevel <= 0 || src.health <= 0) 

上述运营商两者都是logical operators

+0

非常感谢 – user2621004

+2

逻辑运算符也有几个SO线程:http://stackoverflow.com/questions/12332316/logical-operators-in-c –

+0

+1为链接 –

4

这取决于如果你想既要评价为真...

if((powerlevel<=0) && (src.health<=0)) { 
    // do stuff 
} 

...或至少一个...

if((powerlevel<=0) || (src.health<=0)) { 
    // do stuff 
} 

区别在于逻辑AND(& &)或逻辑OR(||)

1

或者,如果你不想使用& &您可以使用三元运算符

#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; 
} 
+0

我真的很喜欢三元运算符,但' (x?true:false)'...?哎呀! ;-) –

+0

是的,我有点同意,但其他人已经提出了&&版本,我想我只是向他介绍这个概念,因为他正在寻求一种方法来做到这一点。 – bjackfly

1

只是一个aternative如果它是有意义的(有时)。

Both true: 
if (!(src.health > 0 || powerlevel > 0)) {} 

at least one is true: 
if (!(src.health > 0 && powerlevel > 0)) {}