问题
I have to perform logic if a number is x times bigger than another number.
// The distance between two candles
var distance = Math.Abs(firstAggregationUpperValue - currentCandleUpperValue);
// How many times is the distance bigger than firstAggregationDifference
var times = distance / firstAggregationDifference;
I have to perform the following checks for times
:
- 7 or above and below 9 (times >= 7 && times < 9)
- 9 or above and below 12 (times >= 9 && times < 12)
- 12 or above and below 16 (times >= 12 && times < 16)
- etc.
Assuming times is starting at 3 times bigger, the sequence is: 4 -> 2 -> 3.
- 3 + 4 = 7 (times >= 7 && times < 9)
Note that 4 there. The next one is + 2
.
- 7 + 2 = 9 (times >= 9 && times < 12)
Note that 2. The next one is + 3
.
- 9 + 3 = 12 (times >= 12 && times < 16)
Note 3 there. The next one is again + 4
.
- 12 + 4 = 16 (times >= 16 && times < 18)
- and so on
What's the best way to do that? I just don't want to hard-code 7, 9, 12, 16, 18, etc.
回答1:
This is a working solution using loops.
int n = 3;
for (int j = 0; j < 10; j++)
{
for (int i = 0; i < parameters.Length; i++)
{
var nextParameter = parameters[(i + 1) % parameters.Length];
var firstPart = n + parameters[i];
var secondPart = n + parameters[i] + nextParameter;
if (times >= firstPart)
{
Console.WriteLine($"times >= {firstPart} (&& times < {secondPart}) ({n} + {parameters[i]})");
}
n += parameters[i];
}
}
Output:
if times == 44 =>
times >= 7 (&& times < 9) (3 + 4)
times >= 9 (&& times < 12) (7 + 2)
times >= 12 (&& times < 16) (9 + 3)
times >= 16 (&& times < 18) (12 + 4)
times >= 18 (&& times < 21) (16 + 2)
times >= 21 (&& times < 25) (18 + 3)
times >= 25 (&& times < 27) (21 + 4)
times >= 27 (&& times < 30) (25 + 2)
times >= 30 (&& times < 34) (27 + 3)
times >= 34 (&& times < 36) (30 + 4)
times >= 36 (&& times < 39) (34 + 2)
times >= 39 (&& times < 43) (36 + 3)
times >= 43 (&& times < 45) (39 + 4)
来源:https://stackoverflow.com/questions/58620479/perform-consecutive-checks