![]() |
![]() |
![]() |
![]() |
![]() |
|
Suppose, for example, that you want your analyze_trades program to
have two ways of operating, one fast and approximate and another slower,
but more accurate. The mean_price function, as defined, is
completely accurate:
double mean_price (struct trade **array, int length) {
int counter; double sum = 0.0;
for (counter = 0; counter < length; ++counter)
sum = sum + array[counter] -> price;
return sum / counter;
}
Here is another, faster version of mean_price that bases its result
on only every second element in the array:
double mean_price (struct trade **array, int length) {
int counter, selector; double sum = 0.0;
for (counter = 0, selector = 0;
selector < length;
++counter, selector = selector + 2)
sum = sum + array[selector] -> price;
return sum / counter;
}
You can combine the two versions of mean_price, controlling speed
versus accuracy via a global variable named mode. If the value of
mode is 0, you have high speed; if the value of mode is
1, you have high accuracy:
int mode = default value, 0 or 1
...
double mean_price (struct trade **array, int length) {
int counter, selector, increment; double sum = 0.0;
if (mode)
increment = 2;
else
increment = 1;
for (counter = 0, selector = 0;
selector < length;
++counter, selector = selector + increment)
sum = sum + array[selector] -> price;
return sum / counter;
}