0

目的 c と条件に小さな問題があります。私が与えた 6 つの条件で、少なくとも 3 つが正しいと検証されなければならないことをどのように示すことができますか?

ご回答ありがとうございます。

4

5 に答える 5

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
 }
于 2013-03-19T17:13:40.200 に答える
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
}
于 2013-03-19T17:14:09.670 に答える
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;
于 2013-03-19T17:14:51.600 に答える
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
}
于 2013-03-19T17:26:26.077 に答える
0
 @interface Conditions
 @property (nonatomic, strong) NSMutableArray *conditions;

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

条件のリストをオブジェクトにラップします。3 つの条件が満たされているかどうかを知る必要がある場合:

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

これはやり過ぎです - おそらくばかげたやり過ぎです - これが使い捨てのプロジェクトである場合。ただし、長期的なメンテナンスが問題になる場合、これにより、条件が実装の詳細から切り離されます。条件の長いリストを避けます。条件を簡単に追加または変更できます。論理が複雑になった場合は、オブジェクト指向の優れたインターフェイスで対処できます。(Condition はおそらく、オブジェクトではなく Facade として動作するプロトコルです)。

于 2013-03-19T17:40:01.373 に答える