Reputation: 11
if ((((a > 0) && ((b > 0) || (c> 0) || (d> 0) || (e> 0))) ||
((a1 > 0) && ((b> 0) || (c > 0) || (d > 0) || (e> 0))) ||
((a2 > 0) && ((b> 0) || (c> 0) || (d> 0) || (e> 0))) ||
((a3> 0) && ((b> 0) || c> 0) || (d> 0) || (e> 0)))) &&
((75.5 > d1 && d1 > 74.5) || (75.5 > d2 && d2 > 74.5)))
{
//do something
}
just want to make the condition of the IF as the following:
(a > 0 and( b > 0 or c > 0 or d > 0 or e > 0)) and ((d1< 75.5 and d1>74.5 ) or (d2<75.5 and d2>74.5)) or (a1 > 0 and( b > 0 or c > 0 or d > 0 or e > 0)) and ((d1< 75.5 and d1>74.5 ) or (d2<75.5 and d2>74.5)) or (a2 > 0 and( b > 0 or c > 0 or d > 0 or e > 0)) and ((d1< 75.5 and d1>74.5 ) or (d2<75.5 and d2>74.5)) or (a3 > 0 and( b > 0 or c > 0 or d > 0 or e > 0)) and ((d1< 75.5 and d1>74.5 ) or (d2<75.5 and d2>74.5))
for the same conditions for a1 to a3
cos I have created a for loop before these code to do some checking , and those a,a1,a2,a3,b,c,d,e are the ints which have added 1 under some special condition in the for loop, and i just want to do some further grouping in this if() and just wonder if this multi "Ands" and "Ors" will work or not
Upvotes: 1
Views: 151
Reputation: 15150
You can make a helper method for checking the repetitive code like:
Func<bool> conditionExpression => (int a, int b, int c, int d, int e) =>
{
return a > 0 && (b | c |d | e) > 0;
}
bool dWithinRange = (d1 < 75.5 && d1 > 74.5 ) || (d2 < 75.5 and d2 > 74.5);
if (conditionExpression(a, b, c, d, e) &&
conditionExpression(a1, b1, c1, d1, e1) &&
conditionExpression(a2, b2, c2, d2, e2) &&
conditionExpression(a3, b3, c3, d3, e3) &&
dWithinRange
{
// finally
}
I queess however that the most helpfull modification would be for giving your variables understandable names. It's unlikely that a reader of your code will understand what d1 is and why it has to be smaller than ...
Upvotes: 0
Reputation: 12680
I would break this out into more booleans to simplify it
bool biggerZero = (b > 0) || (c> 0) || (d> 0) || (e> 0));
bool anAzero = a > 0 || a1 > 0 || a2 > 0 || a3 > 0;
bool d1range = 75.5 > d1 && d1 > 74.5;
bool d2range = 75.5 > d2 && d2 > 74.5;
bool solution = anAzero && biggerZero && (d1range || d2range);
Upvotes: 3
Reputation: 150228
Generally it is much clearer to place the common subexpressions in separate variables when they are repeated in a complex expression. That should make no difference to the compiler in terms of optimization.
Your parenthesis are not balanced so I'm not 100% sure what your code is expressing, but for example you could declare
bool aThroughEGreaterEqualZero = (b > 0) || (c> 0) || (d> 0) || (e> 0);
and use that in place of all occurrences of that evaluation in your if
.
For the sake of the next person to maintain the code, I would break down the expression in the if
statement into a number of meaningfully-named variables, and then use those variables in the actual if
.
Upvotes: 1