2013-03-19 55 views
0

我对目标c和条件有一个小问题。我们如何证明,在6个条件中,我至少给出3个条件必须被验证为正确的?目标中的多个条件C

谢谢你的回答!

回答

1
int counter = 0; 
if (condition1) counter++; 
if (condition2) counter++; 
if (condition3) counter++; 
if (condition4) counter++; 
if (condition5) counter++; 
if (condition6) counter++; 
if (counter >= 3) { 
    // something 
} 
+0

让我了5秒 – 2013-03-19 17:14:37

+0

非常感谢您为快速和完美的帮助 – user2187565 2013-03-19 17:17:26

3

你可以做到这一点是:

int validated=0; 

if(condition1){ 
    validated++; 
} 
if(condition2){ 
    validated++; 
} 
if(condition3){ 
    validated++; 
} 
if(condition4){ 
    validated++; 
} 
if(condition5){ 
    validated++; 
} 
if(condition6){ 
    validated++; 
} 
if(validated>=3){ 
     //do your stuffs 
} 
+0

+1为更快:) – DrummerB 2013-03-19 17:14:29

0

你可以尝试计算正确的条件:

伪代码:已经给了

int counter = 0; 
if(A) counter++; 
if(B) counter++; 
if(C) counter++; 
if(D) counter++; 
if(E) counter++; 
if(F) counter++; 

if(counter >= 3){ 
//do stuff here 
} 
counter = 0; 
+0

'== true'?是吗? – 2013-03-19 17:15:20

+0

geez,你们很快。 – adamup 2013-03-19 17:16:33

+1

可能是(!(A == true)== 0) – 2013-03-19 17:16:49

0

除了答案,这是一个更灵活的解决方案,适用于多种条件:

int conditions[6] = {condition1, condition2, condition3, 
        condition4, condition5, condition6}; 
int counter = 0; 
for (int i = 0; i < sizeof(conditions)/sizeof(int); i++) { 
    counter += conditions[i]; // Assuming your conditions are 0 or 1. 
} 
if (counter >= 3) { 
    // do something 
} 
+0

新实验:) – 2013-03-19 17:27:54

+0

你可以优化这个代码,在for循环中,if(counter == 3)break;':D – 2013-03-19 17:32:25

0
@interface Conditions 
@property (nonatomic, strong) NSMutableArray *conditions; 

- (void) addCondition: (Condition*) theCondition; 
- (NSInteger) count; 
- (NSInteger) satisfying: (void (^block)(Condition*) ); 
@end 

包裹在一个对象的条件清单。当你需要知道,如果满足这三个条件:

if ([self.conditions satisfying: ^(Condition *c){ return [c isSatisfied]; })>3) {...}; 

这是矫枉过正 - 也许是可笑的矫枉过正 - 如果这是一个一次性的项目。但是,如果长期维护是一个问题,这将使条件与实施细节脱节。您避免了一长串条件。您可以轻松地添加或更改条件,并且如果其逻辑变得复杂,则可以有一个很好的面向对象的界面来处理它。 (条件可能是作为门面而不是对象操作的协议)。